实现代码
在控制器中这样写:
$this->view->params['customParam'] = 'customValue';
在视图中这样调用:
echo $this->params['customParam'];
实现原理
在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。