view_renderers.md 2.09 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
		),
	),
)
```

Alexander Makarov committed
30 31 32
Note that Smarty and Twig are not bundled with Yii and you have to download and
unpack these yourself and then specify `twigPath` and `smartyPath` respectively.

33 34 35
Twig
----

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

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

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
### 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

60 61 62
Smarty
------

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

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

### 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