Yii Application Development Cookbook(Second Edition)
上QQ阅读APP看书,第一时间看更新

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...

  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 home page 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 the decorator template using a second parameter of beginContent, such as the one we did for the author.

Note

Note that we have used //decorators/quote as the view path. This means that the view will be searched starting from either the theme views root or the application views root.

There's more…

The following URL provides more details about decorators:

http://www.yiiframework.com/doc/api/CContentDecorator/

See also

  • The Using the controller context in a view recipe