Stories

Detail Return Return

Yii2 controller 傳值給layout - Stories Detail

在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 Avatar tangzhangming Avatar tangqingfeng Avatar
Favorites 3 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.