动态

详情 返回 返回

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。

在fecify中就採用了這個技術點,把 controller 傳值給layout,解決了難題,希望可以幫助大家。

user avatar xiaotuyu 头像 tangzhangming 头像 tangqingfeng 头像
点赞 3 用户, 点赞了这篇动态!
点赞

Add a new 评论

Some HTML is okay.