Twig不在Yii2工作

时间:2017-07-04 15:30:23

标签: php yii2 twig yii2-advanced-app yii-extensions

我想在 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 %}

1 个答案:

答案 0 :(得分:1)

我解决了这个问题:

我修改了文件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