Yii2 controller 传值给layout

2年前 (2022) 程序员胖胖胖虎阿
133 0 0

在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,解决了难题,希望可以帮助大家。

Yii2 controller 传值给layout

Yii2 controller 传值给layout

版权声明:程序员胖胖胖虎阿 发表于 2022年10月4日 上午10:32。
转载请注明:Yii2 controller 传值给layout | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...