yii2 默認(rèn)使用PHP 和html 混合的方式來寫視圖層,如果您已經(jīng)非常習(xí)慣使用twig的語法,可以選擇使用twig視圖引擎。
github 已經(jīng)有人提供了這樣的vendor ,可以直接composer 配置一下進(jìn)行使用。
composer.json 文件 require 添加 "yiisoft/yii2-twig": "*" 然后 composer update
(推薦教程:yii框架)
前往common/config 下 main.php 加上配置
[ 'components' => [ 'view' => [ 'class' => 'yiiwebView', 'renderers' => [ 'tpl' => [ 'class' => 'yiismartyViewRenderer', //'cachePath' => '@runtime/Smarty/cache', ], 'twig' => [ 'class' => 'yiitwigViewRenderer', 'cachePath' => '@runtime/Twig/cache', // Array of twig options: 'options' => [ 'auto_reload' => true, ], 'globals' => ['html' => 'yiihelpersHtml'], 'uses' => ['yiibootstrap'], ], // ... ], ], ],]
其中tpl 的配置是smarty 引擎。如果不使用smarty 可以不配置。接下來就可以去控制器下使用了。
return $this->render('test.twig', ['test' => 'hello,yii']);