Yii Twig extension allows you to define your own syntax and bring regular helper classes into templates. Let's review configuration options.
You can add global helpers or values via the application configuration's globals
variable. You can define both Yii
helpers and your own variables there:
'globals' => [
'html' => ['class' => \yii\helpers\Html::class],
'name' => 'Carsten',
'GridView' => ['class' => \yii\grid\GridView::class],
],
Once configured, in your template you can use the globals in the following way:
Hello, {{name}}! {{ html.a('Please login', 'site/login') | raw }}.
{{ GridView.widget({'dataProvider' : provider}) | raw }}
You can define additional functions like the following:
'functions' => [
'rot13' => 'str_rot13',
'truncate' => '\yii\helpers\StringHelper::truncate',
new \Twig\TwigFunction('rot14', 'str_rot13'),
new \Twig\TwigFunction('add_*', function ($symbols, $val) {
return $val . $symbols;
}, ['is_safe' => ['html']]),
'callable_add_*' => function ($symbols, $val) {
return $val . $symbols;
},
'sum' => function ($a, $b) {
return $a + $b;
}
],
In template they could be used like the following:
{{ rot13('test') }}
{{ truncate(post.text, 100) }}
{{ rot14('test') }}
{{ add_42('answer') }}
{{ callable_add_42('test') }}
{{ sum(1, 2) }}
Additional filters may be added via the application configuration's filters
option:
'filters' => [
'jsonEncode' => '\yii\helpers\Json::htmlEncode',
new \Twig\TwigFilter('rot13', 'str_rot13'),
new \Twig\TwigFilter('add_*', function ($symbols, $val) {
return $val . $symbols;
}, ['is_safe' => ['html']]),
'callable_rot13' => function($string) {
return str_rot13($string);
},
'callable_add_*' => function ($symbols, $val) {
return $val . $symbols;
}
],
Then in the template you can apply filter using the following syntax:
{{ model|jsonEncode }}
{{ 'test'|rot13 }}
{{ 'answer'|add_42 }}
{{ 'test'|callable_rot13 }}
{{ 'answer'|callable_add_42 }}
Additional paths may be added via the application configuration's twigFallbackPaths
option:
'twigFallbackPaths' => [
'layouts' => '@app/views/layouts' //it is possible to use yii2-alises
]
Then they could be used in a template:
{% extends '@layouts/main.twig %}
To include twig-profile data in trace log you need to add the extension
'extensions' => [
\yii\twig\Profile::class
]
Profile writes log only debug mode.
Using a profile affects performance.
This extension provides a ViewRenderer
that would allow you to use Twig view template engine.