yii2 使用twig 模板引擎


yii2 默認使用PHP 和html 混合的方式來寫視圖層,但我個人還是喜歡純模板語言的方式。而且已經非常習慣使用twig的語法,最近想使用yii2進行開發,所以還是選擇使用twig視圖引擎。

    github 已經有人提供了這樣的vendor ,可以直接comoser 配置一下進行使用。

composer.json 文件 require 添加 "yiisoft/yii2-twig": "*" 然后 composer update

   前往common/config 下 main.php 加上配置

[    'components' =>
      [        'view' => [           
                       'class' => 'yii\web\View',           
                          'renderers' => [               
                           'tpl' => [                   
                            'class' => 'yii\smarty\ViewRenderer',                   
                             //'cachePath' => '@runtime/Smarty/cache',              
                               ],               
                            'twig' => [                   
                             'class' => 'yii\twig\ViewRenderer',                
                             'cachePath' => '@runtime/Twig/cache',                 
                               // Array of twig options:                   
                                'options' => [                        
                                    'auto_reload' => true,                   
                                     ],                   
                             'globals' => ['html' => '\yii\helpers\Html'],          
                              'uses' => ['yii\bootstrap'],               
                        ],               
                                // ...         
                 ],      
              ],   
       ],]

    其中tpl 的配置是smarty 引擎。如果不使用smarty 可以不配置。接下來就可以去控制器下使用了。

return $this->render('test.twig', ['test' => 'hello,yii']);

   github地址:https://github.com/yiisoft/yii2/blob/master/docs/guide/tutorial-template-engines.md


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM