/ yi2

yii2-twig

https://twig.symfony.com/doc/2.x/

https://github.com/yiisoft/yii2-twig/blob/master/docs/guide/README.md

Assets

{{ register_asset_bundle('yii/web/JqueryAsset') }}

Importing widgets namespaces and classes

Namespace import:
{{ use('/app/widgets') }}

Class import:
{{ use('/yii/widgets/ActiveForm') }}

Aliased class import:
{{ use({'alias' : '/app/widgets/MyWidget'}) }}

Importing other classes

除了 widgets 和 asset ,类似 Model 类必须通过全局形式导入:

这样不会生效:

{{ use('yii/helpers/Url') }}
<h1>{{ Url.base(true) }}</h1>

这样也不会生效:

{{ use ('app/models/MyClass') }}  
{{ MyClass.helloWorld() }}

必须通过全局导入:

// ....
'view' => [
    'class' => 'yii\web\View',
    'renderers' => [
        'twig' => [
            'class' => 'yii\twig\ViewRenderer',
            'cachePath' => '@runtime/Twig/cache',
            'options' => [
                'auto_reload' => true,
            ],
            'globals' => [
                'Url' => ['class' => '\yii\helpers\Url'],
                'MyClass' => ['class' => '\frontend\models\MyClass'],
            ],
        ],
    ],
],
// ....

这样才会生效:

Urls

有两种生成 url 的方式:

<a href="{{ path(['blog/view'], {'alias' : post.alias}) }}">{{ post.title }}</a>
<a href="{{ url(['blog/view'], {'alias' : post.alias}) }}">{{ post.title }}</a>

path 生成相对路由,而 url 生成绝对路由。 内部实现都是使用的 [[\yii\helpers\Url::to]].

Model

{{ MyClass.helloWorld() }}

Additional variables

  • app, which equates to \Yii::$app
  • this, which equates to the current View object

Blocks

You can set blocks the following way:

{{ void(this.beginBlock('block1')) }}
now, block1 is set
{{ void(this.endBlock()) }}

Then, in the layout view, render the blocks:

{{ this.blocks['block1'] }}

Layouts

Referencing other templates

There are two ways of referencing templates in include and extends statements:

{% include "comment.twig" %}
{% extends "post.twig" %}

{% include "@app/views/snippets/avatar.twig" %}
{% extends "@app/views/layouts/2columns.twig" %}

Layouts and Widgets

https://github.com/yiisoft/yii2-twig/blob/master/docs/guide/layouts-and-widgets.md

从 view 向 layout 传值

定义变量:

{% set result = my_function({'a' : 'b'}) %}
{% set result = myObject.my_function({'a' : 'b'}) %}

输出变量:

{{ my_function({'a' : 'b'}) }}
{{ myObject.my_function({'a' : 'b'}) }}

ErrorAction

public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
                // 这里要指定使用的 view 文件
                'view' => 'error.twig',
            ],
        ];
    }

Wdiget

{{ use('yii/widgets/Breadcrumbs') }}
{{ breadcrumbs_widget({
    'links': [ this.title ],
}) }}