0.首先声明:
$content = $this->renderPartial('index', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider,]); //加载视图文件,返回字符串
return $this->renderContent($content); //将字符串传递给布局文件echo $content;输出
//以上两行代码,相当于下面这一行代码,等价的
return $this->render('index', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider,]);
那么如何实现在renderContent()里面传递数组呢?这样的话,我就可以为布局文件传递多个视图文件字符串了,可以得到很大的扩展。
1.重写方法renderContent().此方法在yii2\base\Controller.php里面。
原代码如下:
/**
* Renders a static string by applying a layout.
* @param string $content the static string being rendered
* @return string the rendering result of the layout with the given static string as the `$content` variable.
* If the layout is disabled, the string will be returned back.
* @since 2.0.1
*/
public function renderContent($content)
{
$layoutFile = $this->findLayoutFile($this->getView());
if ($layoutFile !== false) {
return $this->getView()->renderFile($layoutFile, ['content' => $content], $this);
} else {
return $content;
}
}
重写代码如下:
public function renderContent($content)
{
$layoutFile = $this->findLayoutFile($this->getView());
if ($layoutFile !== false) {
if(is_array($content)){
return $this->getView()->renderFile($layoutFile, $content, $this);
}else{
return $this->getView()->renderFile($layoutFile, ['content'=>$content], $this);
}
} else {
return $content;
}
}
2在控制器中的使用如下:
$content = $this->renderPartial('index', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider,]);
$content2 = $this->renderPartial('lixian');
return $this->renderContent(['content'=>$content,'lixian'=>$content2]);
//当然你也可以使用一个变量而不用数组,对之前的用法没有任何影响
3当然这也不影响你直接使用render()方法。
但是在布局文件中我们使用变量时要注意,因为很多地方都用到布局文件,所以不一定都要几个变量,可能一些地方并没有你定义的变量,所以我们就要判定以下到底有没有这个变量。代码如下:
<?php
if(isset($lixian)){
echo $lixian;
}
?>
好了,现在就可以使用多个变量了,可以自定义n个变量,但一定要记得判定哦。