使用模板引擎


默认情况下,Yii 使用 PHP 作为其默认的模板引擎语言,但是,你可以配置 Yii 以扩展的方式支持其他的渲染引擎,比如 Twig 或 Smarty等。

组件 view 就是用于渲染视图的。你可以重新配置这个组件的行为以增加一个自定义的模板引擎。

  1. [
  2.     'components' => [
  3.         'view' => [
  4.             'class' => 'yii\web\View',
  5.             'renderers' => [
  6.                 'tpl' => [
  7.                     'class' => 'yii\smarty\ViewRenderer',
  8.                     //'cachePath' => '@runtime/Smarty/cache',
  9.                 ],
  10.                 'twig' => [
  11.                     'class' => 'yii\twig\ViewRenderer',
  12.                     'cachePath' => '@runtime/Twig/cache',
  13.                     // Array of twig options:
  14.                     'options' => [
  15.                         'auto_reload' => true,
  16.                     ],
  17.                     'globals' => ['html' => '\yii\helpers\Html'],
  18.                     'uses' => ['yii\bootstrap'],
  19.                 ],
  20.                 // ...
  21.             ],
  22.         ],
  23.     ],
  24. ]

在上述的代码中, Smarty 和 Twig 都被配置以让视图文件使用。但是,为了让扩展安装到项目中,你同样需要修改你的 composer.json 文件,如下:

  1. "yiisoft/yii2-smarty": "*",
  2. "yiisoft/yii2-twig": "*",

上述代码需要增加到 composer.jsonrequire 节中。在做了上述修改,并保存后,你可以运行 composer update --prefer-dist 命令来安装扩展。

对于特定模板引擎的使用详细,请参考其文档: