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

2022-01-04 00:00:00 php yii model-view-controller

在 Yii 中,有没有办法使用与控制器定义的不同的 layout 来渲染单个动作?我有一个动作,我想以与其他动作不同的方式格式化,如果可能的话,文档中并不清楚.

In Yii, is there a way to render a single action using a different layout than 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.

推荐答案

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

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

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/

:::

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

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

$this->layout = 'nameOfYourAltLayout';

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

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.

相关文章