Using decorators
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...
- First, we will create a decorator file,
protected/views/decorators/quote.php
:<div class="quote"> “<?php echo $content?>”, <?php echo $author?> </div>
- 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()?>
- Now, your home page should include the following markup:
<div class="quote"> “If anything bad can happen, it probably will”, 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 the decorator template using a second parameter of beginContent
, such as the one we did for the author.
There's more…
The following URL provides more details about decorators:
See also
- The Using the controller context in a view recipe