From 9cb0a510cb696dc700cfd6e39635ca8c350d6f1a Mon Sep 17 00:00:00 2001 From: cansozeri Date: Mon, 16 Jun 2014 21:44:57 +0300 Subject: [PATCH] Update ViewRenderer.php I want to use my layouts in a different folder that calls base or main layout in project and use them every twig files that can be extended. views | site |index.htm | layouts |main.htm Now If I call render like this I can not extend main.htm, because it is not in site view folder, it is in the layouts folder. public function actionIndex() { return $this->render('index.htm'); } http://stackoverflow.com/questions/24247569/twig-template-layout-yii2-framework So I change the file and now I can define layouts folder with Twig_Loader_Filesystem and after that in function render, I can addPath my file folder path site/index.htm .. so twig search the files in two folders - layouts and site folders. If you want we can change the $define_layout as an array and from config file we can send more than one folders that can twig search for. If there is another simple way to do this I would be very happy to learn how can I do this .. Regards, --- extensions/twig/ViewRenderer.php | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/extensions/twig/ViewRenderer.php b/extensions/twig/ViewRenderer.php index 0d6ff9c9743..8b6e120b79d 100644 --- a/extensions/twig/ViewRenderer.php +++ b/extensions/twig/ViewRenderer.php @@ -75,11 +75,30 @@ class ViewRenderer extends BaseViewRenderer /** * @var \Twig_Environment twig environment object that do all rendering twig templates */ + + + public $define_layout = NULL; + /** + * @var string the directory pointing to where the extra layout template folder. + */ + public $twig; + + public $loader; public function init() { - $this->twig = new \Twig_Environment(null, array_merge([ + // Adding extra template layout + if (!empty($this->define_layout)) { + + $this->loader = new \Twig_Loader_Filesystem($_SERVER['DOCUMENT_ROOT'].$this->define_layout); + } + else + { + $this->loader = NULL; + } + + $this->twig = new \Twig_Environment($this->loader, array_merge([ 'cache' => Yii::getAlias($this->cachePath), 'charset' => Yii::$app->charset, ], $this->options)); @@ -154,8 +173,16 @@ public function init() public function render($view, $file, $params) { $this->twig->addGlobal('this', $view); - $this->twig->setLoader(new TwigSimpleFileLoader(dirname($file))); + if($this->loader) + { + $this->loader->addPath(dirname($file)); + } + else + { + $this->twig->setLoader(new TwigSimpleFileLoader(dirname($file))); + } + return $this->twig->render(pathinfo($file, PATHINFO_BASENAME), $params); }