tutorial-template-engines.md 7.05 KB
Newer Older
1 2 3
Using template engines
======================

4
> Note: This section is under development.
Qiang Xue committed
5

Larry Ullman committed
6
By default, Yii uses PHP as its template language, but you can configure Yii to support other rendering engines, such as
7
[Twig](http://twig.sensiolabs.org/) or [Smarty](http://www.smarty.net/).
8

Larry Ullman committed
9
The `view` component is responsible for rendering views. You can add a custom template engine by reconfiguring this
10
component's behavior:
11 12

```php
Alexander Makarov committed
13
[
14 15 16 17 18 19 20 21 22 23 24 25 26
    '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',
                    //'options' => [], /*  Array of twig options */
                    'globals' => ['html' => '\yii\helpers\Html'],
27
                    'uses' => ['yii\bootstrap'],
28 29 30 31 32
                ],
                // ...
            ],
        ],
    ],
Alexander Makarov committed
33
]
34 35
```

Larry Ullman committed
36 37
In the code above, both Smarty and Twig are configured to be useable by the view files. But in order to get these extensions into your project, you need to also modify
your `composer.json` file to include them, too:
38 39 40 41 42

```
"yiisoft/yii2-smarty": "*",
"yiisoft/yii2-twig": "*",
```
43
That code would be added to the `require` section of `composer.json`. After making that change and saving the file, you can install the extensions by running `composer update --prefer-dist` in the command-line.
44 45 46 47

Twig
----

48 49
To use Twig, you need to create templates in files that have the `.twig` extension (or use another file extension but
configure the component accordingly). Unlike standard view files, when using Twig you must include the extension
50
in your `$this->render()` controller call:
51 52

```php
53
return $this->render('renderer.twig', ['username' => 'Alex']);
54 55
```

56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
### Template syntax

The best resource to learn Twig basics is its official documentation you can find at
[twig.sensiolabs.org](http://twig.sensiolabs.org/documentation). Additionally there are Yii-specific addtions
described below.

#### Method and function calls

If you need result you can call a method or a function using the following syntax:

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

If you need to echo result instead of assigning it to a variable:

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

In case you don't need result you shoud use `void` wrapper:

```
{{ void(my_function({'a' : 'b'})) }}
82
{{ void(myObject.my_function({'a' : 'b'})) }}
83 84
```

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
#### Importing namespaces and classes

You can import additional classes and namespaces right in the template:

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

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

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

#### Widgets

Extension helps using widgets in convenient way converting their syntax to function calls:

```
{{ use('yii/bootstrap') }}
{{ nav_bar_begin({
    'brandLabel': 'My Company',
}) }}
    {{ nav_widget({
        'options': {
            'class': 'navbar-nav navbar-right',
        },
        'items': [{
            'label': 'Home',
            'url': '/site/index',
        }]
    }) }}
{{ nav_bar_end() }}
```

In the template above `nav_bar_begin`, `nav_bar_end` or `nav_widget` consists of two parts. First part is widget name
coverted to lowercase and underscores: `NavBar` becomes `nav_bar`, `Nav` becomes `nav`. `_begin`, `_end` and `_widget`
are the same as `::begin()`, `::end()` and `::widget()` calls of a widget.

One could also use more generic `widget_end()` that executes `Widget::end()`.

#### Assets

Assets could be registered the following way:

```
{{ use('yii/web/JqueryAsset') }}
{{ register_jquery_asset() }}
```

In the call above `register` identifies that we're working with assets while `jquery_asset` translates to `JqueryAsset`
class that we've already imported with `use`.

139
#### Forms
Alexander Makarov committed
140

141
You can build forms the following way:
142

Alexander Makarov committed
143
```
144 145
{{ use('yii/widgets/ActiveForm') }}
{% set form = active_form_begin({
146 147 148 149 150 151 152 153 154
    'id' : 'login-form',
    'options' : {'class' : 'form-horizontal'},
}) %}
    {{ form.field(model, 'username') | raw }}
    {{ form.field(model, 'password').passwordInput() | raw }}

    <div class="form-group">
        <input type="submit" value="Login" class="btn btn-primary" />
    </div>
155
{{ active_form_end() }}
Alexander Makarov committed
156 157 158
```


159
#### URLs
Alexander Makarov committed
160

161
There are two functions you can use for building URLs:
162 163 164

```php
<a href="{{ path('blog/view', {'alias' : post.alias}) }}">{{ post.title }}</a>
Alexander Makarov committed
165
<a href="{{ url('blog/view', {'alias' : post.alias}) }}">{{ post.title }}</a>
166 167
```

Alexander Makarov committed
168
`path` generates relative URL while `url` generates absolute one. Internally both are using [[\yii\helpers\Url]].
169

170
#### Additional variables
171

172
Within Twig templates the following variables are always defined:
173 174 175

- `app`, which equates to `\Yii::$app`
- `this`, which equates to the current `View` object
176

177 178 179 180 181 182
### Additional configuration

Yii Twig extension allows you to define your own syntax and bring regular helper classes into templates. Let's review
configuration options.

#### Globals
183

184 185
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:
186 187 188

```php
'globals' => [
189 190
    'html' => '\yii\helpers\Html',
    'name' => 'Carsten',
191
    'GridView' => '\yii\grid\GridView',
192 193 194
],
```

Larry Ullman committed
195
Once configured, in your template you can use the globals in the following way:
196 197

```
yupe committed
198
Hello, {{name}}! {{ html.a('Please login', 'site/login') | raw }}.
199 200

{{ GridView.widget({'dataProvider' : provider}) | raw }}
201 202
```

203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
#### Functions

You can define additional functions like the following:

```php
'functions' => [
    'rot13' => 'str_rot13',
    'truncate' => '\yii\helpers\StringHelper::truncate',
],
```

In template they could be used like the following:

```
`{{ rot13('test') }}`
`{{ truncate(post.text, 100) }}`
```

#### Filters
222

Larry Ullman committed
223
Additional filters may be added via the application configuration's `filters` option:
224 225 226

```php
'filters' => [
227
    'jsonEncode' => '\yii\helpers\Json::encode',
228 229 230
],
```

231
Then in the template you can apply filter using the following syntax:
232 233 234 235 236 237

```
{{ model|jsonEncode }}
```


238 239 240
Smarty
------

Larry Ullman committed
241 242
To use Smarty, you need to create templates in files that have the `.tpl` extension (or use another file extension but configure the component accordingly). Unlike standard view files, when using Smarty you must include the extension in your `$this->render()`
or `$this->renderPartial()` controller calls:
243 244

```php
245
return $this->render('renderer.tpl', ['username' => 'Alex']);
246 247 248 249
```

### Additional functions

250
Yii adds the following construct to the standard Smarty syntax:
251 252 253 254 255

```php
<a href="{path route='blog/view' alias=$post.alias}">{$post.title}</a>
```

256
Internally, the `path()` function calls Yii's `Url::to()` method.
257 258 259

### Additional variables

260 261 262 263
Within Smarty templates, you can also make use of these variables:

- `$app`, which equates to `\Yii::$app`
- `$this`, which equates to the current `View` object
264