view_renderers.md 1.93 KB
Newer Older
1 2 3
Yii2 view renderers
===================

4 5 6 7 8
By default Yii uses PHP as template language but you can configure it to be able
to render templates with special engines such as Twig or Smarty.

The component responsible for rendering a view is called `view`. You can add
a custom template engines as follows:
9 10 11 12

```php
array(
	'components' => array(
13 14
		'view' => array(
			'class' => 'yii\base\View',
15 16 17 18 19 20
			'renderers' => array(
				'tpl' => array(
					'class' => 'yii\renderers\SmartyViewRenderer',
				),
				'twig' => array(
					'class' => 'yii\renderers\TwigViewRenderer',
21
					'twigPath' => '@app/vendors/Twig',
22 23
				),
				// ...
24
			),
25 26 27 28 29 30 31 32
		),
	),
)
```

Twig
----

33 34
In order to use Twig you need to put you templates in files with extension `.twig`
(or another one if configured differently).
35
Also you need to specify this extension explicitly when calling `$this->render()`
36 37 38 39 40
or `$this->renderPartial()` from your controller:

```php
echo $this->render('renderer.twig', array('username' => 'Alex'));
```
41

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
### Additional functions

Additionally to regular Twig syntax the following is available in Yii:

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

path function calls `Html::url()` internally.

### Additional variables

- `app` = `\Yii::$app`
- `this` = current `View` object

57 58 59
Smarty
------

60 61
In order to use Smarty you need to put you templates in files with extension `.tpl`
(or another one if configured differently).
62
Also you need to specify this extension explicitly when calling `$this->render()`
63
or `$this->renderPartial()` from your controller:
64 65

```php
66 67
echo $this->render('renderer.tpl', array('username' => 'Alex'));
```
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

### Additional functions

Additionally to regular Smarty syntax the following is available in Yii:

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

path function calls `Html::url()` internally.

### Additional variables

- `$app` = `\Yii::$app`
- `$this` = current `View` object