php Yii:使用与控制器布局不同的布局渲染动作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6266649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:50:30  来源:igfitidea点击:

Yii: Render action using different layout than controller's layout

phpmodel-view-controlleryii

提问by Matt Hampel

In Yii, is there a way to render a single action using a different layoutthan that defined for the controller? I have an action that I would like to format differently from the rest, and it's not clear from the documentation if that's possible.

在 Yii 中,有没有办法使用不同于layout为控制器定义的动作来呈现单个动作?我有一个动作,我想与其他动作的格式不同,如果可能的话,从文档中不清楚。

回答by k to the z

I believe on that action you could just call the $layoutvariable.

我相信在那个动作上你可以调用$layout变量。

public function actionYourAction()
{
    $this->layout = 'nameOfYourAltLayout';
}

The instructions in the link below indicate that you will have to set this variable for every action since you can't just set the default public variable and expect the other actions to default back to this.

下面链接中的说明表明您必须为每个操作设置此变量,因为您不能只设置默认公共变量并期望其他操作默认返回此变量。

http://www.yiiframework.com/wiki/28/how-to-implement-multiple-page-layouts-in-an-application/

http://www.yiiframework.com/wiki/28/how-to-implement-multiple-page-layouts-in-an-application/

::Edit::

::编辑::

It seems the best practice here is to define the $layoutvariable in the view script for the particular action that calls it. For example, if your action calls viewscriptone.phpthen the viewscriptone view file would contain:

这里的最佳实践似乎是$layout在视图脚本中为调用它的特定操作定义变量。例如,如果您的操作调用,viewscriptone.php则 viewscriptone 视图文件将包含:

$this->layout = 'nameOfYourAltLayout';

It makes more sense to override here rather than in the controller action. However, as LDG said, if the layout is conditional you should probably keep it in the controller. This information can still be found in the link above under the "Using Layouts" section of the page.

在这里覆盖比在控制器操作中覆盖更有意义。但是,正如 LDG 所说,如果布局是有条件的,您可能应该将其保留在控制器中。此信息仍可在上述页面“使用布局”部分下的链接中找到。

回答by ldg

That wiki entry does a pretty good job in describing how to use layouts, definitely worth a read. I do think you can set a layout default at the start of your controller class and then override that within a particular action function without having to define layout in each action, at least it's worked for me. You can also use the beforeActionfunction for any complex situations. And, as you may already know, you can use renderPartial to bypass the layout entirely.

那个 wiki 条目在描述如何使用布局方面做得很好,绝对值得一读。我确实认为您可以在控制器类的开头设置布局默认值,然后在特定的动作函数中覆盖它,而不必在每个动作中定义布局,至少它对我有用。您还可以将beforeAction函数用于任何复杂情况。而且,您可能已经知道,您可以使用 renderPartial 完全绕过布局。