Yii2 controller 传值给layout

技巧库 · fecommerce · 于 6年前 发布 · 7251 次阅读

原文链接:Yii2 controller 传值给layout

在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。


微信

共收到 3 条回复
forecho#16年前 2 个赞

有一个更简单的方法出自 http://stackoverflow.com/questions/28038912/how-to-pass-param-from-controller-to-layout-in-yii2

在控制器中这样写:

$this->view->params['customParam'] = 'customValue';

在视图中这样调用:

/* @var $this yii\web\View */

echo $this->params['customParam'];
fecommerce#26年前 0 个赞

@forecho #1楼 @forecho #1楼 不错,多谢分享。

e282486518#36年前 0 个赞

其实我最开始都是在controller中定义一个属性,在layout中使用$this->context可以访问。。 现在用的是1楼的方法。

添加回复 (需要登录)
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册