tutorial-template-engines.md 12 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
    'components' => [
        'view' => [
            'class' => 'yii\web\View',
            'renderers' => [
                'tpl' => [
                    'class' => 'yii\smarty\ViewRenderer',
                    //'cachePath' => '@runtime/Smarty/cache',
                ],
                'twig' => [
                    'class' => 'yii\twig\ViewRenderer',
24 25 26 27 28
                    'cachePath' => '@runtime/Twig/cache',
                    // Array of twig options:
                    'options' => [
                        'auto_reload' => true,
                    ],
29
                    'globals' => ['html' => '\yii\helpers\Html'],
30
                    'uses' => ['yii\bootstrap'],
31 32 33 34 35
                ],
                // ...
            ],
        ],
    ],
Alexander Makarov committed
36
]
37 38
```

Larry Ullman committed
39 40
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:
41 42 43 44 45

```
"yiisoft/yii2-smarty": "*",
"yiisoft/yii2-twig": "*",
```
46
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.
47 48 49 50

Twig
----

51 52
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
53
in your `$this->render()` controller call:
54 55

```php
56
return $this->render('renderer.twig', ['username' => 'Alex']);
57 58
```

59 60 61
### Template syntax

The best resource to learn Twig basics is its official documentation you can find at
62
[twig.sensiolabs.org](http://twig.sensiolabs.org/documentation). Additionally there are Yii-specific syntax extensions
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
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'})) }}
85
{{ void(myObject.my_function({'a' : 'b'})) }}
86 87
```

88 89 90 91 92 93 94 95 96
#### Setting object properties

There's a special function called `set` that allows you to set property of an object. For example, the following
in the template will change page title:

```
{{ set(this, 'title', 'New title') }}
```

97 98 99 100 101 102 103 104 105 106 107 108
#### 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:
109
{{ use({'alias' : '/app/widgets/MyWidget'}) }}
110 111
```

112
#### Referencing other templates
113

114
There are two ways of referencing templates in `include` and `extends` statements:
115 116 117

```
{% include "comment.twig" %}
118
{% extends "post.twig" %}
119 120 121 122 123

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

124 125
In the first case the view will be searched relatively to the current template path. For `comment.twig` and `post.twig`
that means these will be searched in the same directory as the currently rendered template.
126 127 128

In the second case we're using path aliases. All the Yii aliases such as `@app` are available by default.

129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
#### 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`.

168
#### Forms
Alexander Makarov committed
169

170
You can build forms the following way:
171

Alexander Makarov committed
172
```
173 174
{{ use('yii/widgets/ActiveForm') }}
{% set form = active_form_begin({
175 176 177 178 179 180 181 182 183
    '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>
184
{{ active_form_end() }}
Alexander Makarov committed
185 186 187
```


188
#### URLs
Alexander Makarov committed
189

190
There are two functions you can use for building URLs:
191 192 193

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

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

199
#### Additional variables
200

201
Within Twig templates the following variables are always defined:
202 203 204

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

206 207 208 209 210 211
### 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
212

213 214
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:
215 216 217

```php
'globals' => [
218 219
    'html' => '\yii\helpers\Html',
    'name' => 'Carsten',
220
    'GridView' => '\yii\grid\GridView',
221 222 223
],
```

Larry Ullman committed
224
Once configured, in your template you can use the globals in the following way:
225 226

```
yupe committed
227
Hello, {{name}}! {{ html.a('Please login', 'site/login') | raw }}.
228 229

{{ GridView.widget({'dataProvider' : provider}) | raw }}
230 231
```

232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
#### 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
251

Larry Ullman committed
252
Additional filters may be added via the application configuration's `filters` option:
253 254 255

```php
'filters' => [
256
    'jsonEncode' => '\yii\helpers\Json::encode',
257 258 259
],
```

260
Then in the template you can apply filter using the following syntax:
261 262 263 264 265 266

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


267 268 269
Smarty
------

270 271 272
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:
273 274

```php
275
return $this->render('renderer.tpl', ['username' => 'Alex']);
276 277
```

278 279 280 281 282 283
### Template syntax

The best resource to learn Smarty template syntax is its official documentation you can find at
[www.smarty.net](http://www.smarty.net/docs/en/). Additionally there are Yii-specific syntax extensions
described below.

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
#### Setting object properties

There's a special function called `set` that allows you to set common properties of the view and controller. Currently
available properties are `title`, `theme` and `layout`:

```
{set title="My Page"}
{set theme="frontend"}
{set layout="main.tpl"}
```

For title there's dedicated block as well:

```
{title}My Page{/title}
```

#### Setting meta tags

Meta tags could be set like to following:

```
{meta keywords="Yii,PHP,Smarty,framework"}
```

There's also dedicated block for description:

```
{description}This is my page about Smarty extension{/description}
```

#### Calling object methods

Sometimes you need calling

#### Importing static classes, using widgets as functions and blocks

You can import additional static classes right in the template:

```
{use class="yii\helpers\Html"}
{Html::mailto('eugenia@example.com')}
```

If you want you can set custom alias:

```
{use class="yii\helpers\Html" as="Markup"}
{Markup::mailto('eugenia@example.com')}
```

Extension helps using widgets in convenient way converting their syntax to function calls or blocks. For regular widgets
function could be used like the following:

```
{use class='@yii\grid\GridView' type='function'}
{GridView dataProvider=$provider}
```

For widgets with `begin` and `end` methods such as ActiveForm it's better to use block:

```
{use class='yii\widgets\ActiveForm' type='block'}
{ActiveForm assign='form' id='login-form' action='/form-handler' options=['class' => 'form-horizontal']}
    {$form->field($model, 'firstName')}
    <div class="form-group">
        <div class="col-lg-offset-1 col-lg-11">
            <input type="submit" value="Login" class="btn btn-primary" />
        </div>
    </div>
{/ActiveForm}
```

If you're using particular widget a lot, it is a good idea to declare it in application config and remove `{use class`
call from templates:
359

360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
```php
'components' => [
    'view' => [
        // ...
        'renderers' => [
            'tpl' => [
                'class' => 'yii\smarty\ViewRenderer',
                'widgets' => [
                    'blocks' => [
                        'ActiveForm' => '\yii\widgets\ActiveForm',
                    ],
                ],
            ],
        ],
    ],
],
```

#### Referencing other templates

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

```
{include 'comment.tpl'}
{extends 'post.tpl'}

{include '@app/views/snippets/avatar.tpl'}
{extends '@app/views/layouts/2columns.tpl'}
```

In the first case the view will be searched relatively to the current template path. For `comment.tpl` and `post.tpl`
that means these will be searched in the same directory as the currently rendered template.

In the second case we're using path aliases. All the Yii aliases such as `@app` are available by default.

#### CSS, JavaScript and asset bundles

In order to register JavaScript and CSS files the following syntax could be used:

```
{registerJsFile url='http://maps.google.com/maps/api/js?sensor=false' position='POS_END'}
{registerCssFile url='@assets/css/normalizer.css'}
```

If you need JavaScript and CSS directly in the template there are convenient blocks:

```
{registerJs key='show' position='POS_LOAD'}
    $("span.show").replaceWith('<div class="show">');
{/registerJs}

{registerCss}
div.header {
    background-color: #3366bd;
    color: white;
}
{/registerCss}
```

Asset bundles could be registered the following way:

```
{use class="yii\web\JqueryAsset"}
{JqueryAsset::register($this)|void}
```

Here we're using `void` modifier because we don't need method call result.

#### URLs

There are two functions you can use for building URLs:
431 432 433

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

437
`path` generates relative URL while `url` generates absolute one. Internally both are using [[\yii\helpers\Url]].
438

439
#### Additional variables
440

441
Within Smarty templates the following variables are always defined:
442 443 444

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

446 447 448 449 450 451 452 453
#### Accessing config params

Yii parameters that are available in your application through `Yii::$app->params->something` could be used the following
way:

```
`{#something#}`
```