Twig 在 Yii2 中不起作用

Twig not working in Yii2

我想在 Yii2 框架中使用 Twig,但它不起作用。

我正在使用 yii2-app-advanced 作为基础项目,但我是 Yii 世界的新手,所以我认为我没有以正确的方式配置 Twig。

首先我使用以下方式下载它:

composer require yiisoft/yii2-twig

然后我按照这个说明操作,但它并不容易理解: https://github.com/yiisoft/yii2-twig/blob/HEAD/docs/guide/installation.md#configuring-application

它说: 为了开始使用 Twig,您需要像下面这样配置视图组件:

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

我必须将此代码粘贴到哪个文件中?


在我的 index.php 文件中,我添加了以下代码,但它不起作用:

{% if true %}
    <p>It is true.</p>
{% else %}
    <p>It is false.</p>        
{% endif %}

我这样做解决了它:

我修改了文件backend/config/main-local-php:

<?php

$config = [
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'CPeTotdTU98geIyM7q0PljmCpJbupPN4',
        ],
        'view' => [
            'class' => 'yii\web\View',
            'renderers' => [
                'twig' => [
                    'class' => 'yii\twig\ViewRenderer',
                    'cachePath' => '@runtime/Twig/cache',
                    // Array of twig options:
                    'options' => [
                        'auto_reload' => true,
                    ],
                    'globals' => [
                        'html' => ['class' => '\yii\helpers\Html'],
                    ],
                    'uses' => ['yii\bootstrap'],
                ],
                // ...
            ],
        ],
    ],
];

if (!YII_ENV_TEST) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
    ];

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
    ];
}

return $config;

SiteController.php 文件有 actionIndex() 函数。我添加了扩展名 .twig:

public function actionIndex()
{
    return $this->render('index.twig');
}

然后我把文件名backend/views/sire/index.php修改为index.twig.