If you are using Yii PHP framework you are using one of the fastest PHP frameworks around. Sometimes there are minor things that we want to do and couldn’t find a document that is to the point and precise in what you are looking after.
This Quick Tip article will show you how to use custom layout for your controllers and actions
Controllers
When you want to use custom layout other than //layouts/main then you can do it in several different ways
Option 1
Include $layout property in your class definition as shown below
1 2 3 |
class CoolController extends Controller { public $layout = "CustomLayout"; } |
Option 2
Use init() method of Controller
1 2 3 4 5 |
class CoolController extends Controller { public function init() { $this->layout = "CustomLayout"; } } |
Option 3
Use beforeAction() to overwrite default value of layout property
1 2 3 4 5 |
class CoolController extends Controller { public function beforeAction() { $this->layout = "CustomLayout"; } } |
Please note that when you do any of the above layout is applied to all action views. If you however want to only apply a custom layout to one of the controller action then you do it this way
Apply custom layout to a Controller Action
1 2 3 4 5 |
class CoolController extends Controller { public function actionTest() { $this->layout = "CustomActionLayout"; } } |
As we see that in above snippet we are overwriting default value of layout property for just our action Test. Other action views will still be rendered in default or controller layout.
I hope that this helps
Leave a Reply