使用装饰器

在Yii中,我们可以将内容封装到一个装饰器中。装饰器的常用方法是布局。当你使用你的控制器的渲染方法渲染一个视图的时候,Yii自动使用主布局装饰它。让我们创建一个简单的装饰器,它会正确的格式化引用。

准备

按照官方指南http://www.yiiframework.com/doc-2.0/guide-start-installation.html的描述,使用Composer包管理器创建一个新的应用。

如何做…

  1. 首先,我们将会创建一个装饰器文件@app/views/decorators/quote.php
  1. <div class="quote">
  2. <h2>&ldquo;<?= $content?>&rdquo;, <?= $author?></h2>
  3. </div>
  1. 现在,使用如下代码替换@app/views/site/index.php文件的内容:
  1. <?php
  2. use yii\widgets\ContentDecorator;
  3. /* @var */
  4. ?>
  5. <?php ContentDecorator::begin([
  6. 'viewFile' => '@app/views/decorators/quote.php',
  7. 'view' => $this,
  8. 'params' => ['author' => 'S. Freud']
  9. ]
  10. );?>
  11. Time spent with cats is never wasted.
  12. <?php ContentDecorator::end();?>
  1. 现在,你的Home页面应该会如下所示:

使用装饰器 - 图1

工作原理…

装饰器非常简单。ContentDecorator::begin()ContentDecorator::end()之间的任何东西都会被渲染到一个$content变量中,并传递到一个装饰器模板中。然后,这个装饰器模板被渲染,并被插入到ContentDecorator::end()被调用的地方中。

我们可以使用ContentDecorator::begin()第二个参数传递额外的变量到装饰器模板中,例如之前的例子中我们传递了author变量。

注意我们使用了@app/views/decorators/quote.php作为视图路径。

参考