官术网_书友最值得收藏!

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
主站蜘蛛池模板: 孟村| 余姚市| 奉化市| 高安市| 武陟县| 宝山区| 乌审旗| 阜康市| 安阳市| 黑河市| 固阳县| 拉萨市| 栖霞市| 龙胜| 石首市| 盐山县| 石首市| 社会| 玛沁县| 海林市| 兴业县| 卓资县| 上栗县| 沙河市| 万年县| 曲水县| 白银市| 黎川县| 南乐县| 黄冈市| 安陆市| 成武县| 剑河县| 西乌珠穆沁旗| 陇南市| 乌鲁木齐市| 郁南县| 舟曲县| 五台县| 扶余县| 长海县|