Fecshop 2017-04-18 15:30:44 8247次浏览 2条评论 1 1 0

原文链接: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。

觉得很赞
您需要登录后才可以评论。登录 | 立即注册