template.md 2.14 KB
Newer Older
1 2 3
Using template engines
======================

Larry Ullman committed
4
By default Yii uses PHP as template language, but you can configure it to support other rendering engines, such as [Twig](http://twig.sensiolabs.org/) or [Smarty](http://www.smarty.net/).
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 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 82 83 84

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

```php
array(
	'components' => array(
		'view' => array(
			'class' => 'yii\base\View',
			'renderers' => array(
				'tpl' => array(
					'class' => 'yii\renderers\SmartyViewRenderer',
				),
				'twig' => array(
					'class' => 'yii\renderers\TwigViewRenderer',
					'twigPath' => '@app/vendors/Twig',
				),
				// ...
			),
		),
	),
)
```

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.

Twig
----

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

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

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

Smarty
------

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

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

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