Tuesday, July 3, 2012

Using decorators in YII frameworks

In Yii, we can enclose content into a decorator. The common usage of decorators is
layout. Yes, when you are rendering a view using the render method of your controller, Yii
automatically decorates it with the main layout. Let's create a simple decorator that will
properly format quotes.
Getting ready
Set up a new application using yiic webapp.
How to do it...
1. First, we will create a decorator file protected/views/decorators/quote.php:
<div class="quote">
&ldquo;<?php echo $content?>&rdquo;, <?php echo $author?>
</div>
2. Now in protected/views/site/index.php, we will use our decorator:
<?php $this->beginContent('//decorators/quote', array('author' =>
'Edward A. Murphy'))?>
If anything bad can happen, it probably will
<?php $this->endContent()?>
3. Now, your homepage should include the following markup:
<div class="quote">
&ldquo;If anything bad can happen, it probably will&rdquo;,
Edward A. Murphy
</div>
How it works...
Decorators are pretty simple. Everything between beginContent and endContent
is rendered into a $content variable and passed into a decorator template. Then, the
decorator template is rendered and inserted in the place where endContent was called. We
can pass additional variables into decorator using a second parameter of beginContent,
such as the one we did for the author.

No comments:

Post a Comment