简体   繁体   中英

Yii: Render action using different layout than controller's 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.

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/

::Edit::

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';

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.

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 beforeAction function for any complex situations. And, as you may already know, you can use renderPartial to bypass the layout entirely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM