在yii2中,咱们通过上面的办法,将controller的数组传递给view
public function actionIndex() { $data = ['xx' => 'yy']; return $this->render($this->action->id,$data); }
在view文件中就能够应用$xx变量了,这个变量的值是’yy’.
当初咱们想给layout外面传递,怎么办呢?上面是原理:
在yii/base/Controller.php中能够看到如下代码:
public function render($view, $params = []) { $content = $this->getView()->render($view, $params, $this); return $this->renderContent($content); }查找renderContent()办法 public function renderContent($content) { $layoutFile = $this->findLayoutFile($this->getView()); if ($layoutFile !== false) { return $this->getView()->renderFile($layoutFile, ['content' => $content], $this); } return $content; }
能够看到,咱们只有重写renderContent()办法,在这个办法的内容局部:
[‘content’ => $content]
在这个数组中,增加上咱们的想要的其余的数组,譬如:
[‘content’ => $content, ‘tt’ => ‘terry’]
咱们就能够在layout外面应用$tt变量了。也就是将controller中的变量传递给layout。
在fecify中就采纳了这个技术点,把 controller 传值给layout,解决了难题,心愿能够帮忙大家。