ViewRenderer.php 1.76 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php
/**
 * Twig view renderer class file.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright &copy; 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
10
namespace yii\twig;
11

Qiang Xue committed
12 13
use Yii;
use yii\base\View;
14
use yii\base\ViewRenderer as BaseViewRenderer;
15
use yii\helpers\Html;
16 17 18 19 20 21 22

/**
 * TwigViewRenderer allows you to use Twig templates in views.
 *
 * @author Alexander Makarov <sam@rmcreative.ru>
 * @since 2.0
 */
23
class ViewRenderer extends BaseViewRenderer
24
{
25
	/**
Qiang Xue committed
26
	 * @var string the directory or path alias pointing to where Twig cache will be stored.
27
	 */
28
	public $cachePath = '@runtime/Twig/cache';
29

30
	/**
31
	 * @var array Twig options
32 33
	 * @see http://twig.sensiolabs.org/doc/api.html#environment-options
	 */
Alexander Makarov committed
34
	public $options = [];
35

36 37 38
	/**
	 * @var \Twig_Environment
	 */
Qiang Xue committed
39
	public $twig;
40 41 42 43

	public function init()
	{
		$loader = new \Twig_Loader_String();
44

Alexander Makarov committed
45
		$this->twig = new \Twig_Environment($loader, array_merge([
Qiang Xue committed
46
			'cache' => Yii::getAlias($this->cachePath),
Alexander Makarov committed
47
		], $this->options));
48

Alexander Makarov committed
49 50
		$this->twig->addFunction('path', new \Twig_Function_Function(function ($path, $args = []) {
			return Html::url(array_merge([$path], $args));
51 52 53
		}));

		$this->twig->addGlobal('app', \Yii::$app);
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
	}

	/**
	 * Renders a view file.
	 *
	 * This method is invoked by [[View]] whenever it tries to render a view.
	 * Child classes must implement this method to render the given view file.
	 *
	 * @param View $view the view object used for rendering the file.
	 * @param string $file the view file.
	 * @param array $params the parameters to be passed to the view file.
	 *
	 * @return string the rendering result
	 */
	public function render($view, $file, $params)
	{
70
		$this->twig->addGlobal('this', $view);
Qiang Xue committed
71
		return $this->twig->render(file_get_contents($file), $params);
72 73
	}
}