crowprince 2016-08-05 12:39:59 4940次浏览 0条评论 4 1 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  
  echo $content;
if(isset($lixian)){  

    echo $lixian;  
}  
?>  

更多文章:http://blog.csdn.net/lx_96?viewmode=contents

觉得很赞
    没有找到数据。
您需要登录后才可以评论。登录 | 立即注册