如何在没有模块的情况下动态设置错误处理程序的布局 [英] How to set layout for errorhandler dynamically without module

查看:20
本文介绍了如何在没有模块的情况下动态设置错误处理程序的布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Yii2 的新手,

I am new in Yii2,

当我开始创建一个网站时,我发现你可以像这样在配置中设置ErrorAction

When I started creating a website, i found that you can set ErrorAction in configuration like this

 'errorHandler' => [
            'errorAction' => 'site/error',

        ],

使用 layout/main.php 中的布局时出现的错误.当访客访问位于视图/站点"中的页面时使用该布局.但是当用户登录视图页面时,位于不同文件夹中的view/band"布局变得完全不同,并且使用layout/BandLayout".我知道你可以像在 BandController 中一样在控制器中动态更改布局

That error using layout from layout/main.php. That layout was used when guest visit the page that located in 'view/site'. But when the user log in the view page locate in different folder which is 'view/band' the layout become totally different and using 'layout/BandLayout'. I know that you can change layout dynamically in controller like i did in BandController

public $layout ='BandLayout';

这将改变view/band"中的整个布局.但是当出现像404"这样的错误时,布局仍然使用 layout/main.php 中的布局.我已经做了一些搜索,但在模块中使用 init() 的解决方案.由于我还没有学习模块,如何在控制器中为错误布局设置布局?

That will change the entire layout in 'view/band'. But when there is an error like '404' the layout still using layout from layout/main.php. I have done some searching but the solution using init() in module. Since i have not learn module, how do I set layout for error layout in controller?

谢谢

推荐答案

您应该在 SiteController 中更改布局,您可以使用 beforeAction,例如:

You should change layout in SiteController, you could use beforeAction, e.g. :

public function beforeAction($action)
{
    if (parent::beforeAction($action)) {
        // change layout for error action
        if ($action->id=='error')
             $this->layout ='BandLayout';
        return true;
    } else {
        return false;
    }
}

这篇关于如何在没有模块的情况下动态设置错误处理程序的布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆