yii 如何在布局文件里面使用多个变量?

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个变量,但一定要记得判定哦。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值