关于yii2:Yii2-controller-传值给layout

7次阅读

共计 809 个字符,预计需要花费 3 分钟才能阅读完成。

在 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,解决了难题,心愿能够帮忙大家。

正文完
 0