Search code examples
phpyiisidebar

Dynamic layout in Yii


I have a Yii application and in the layout I have a static sidebar. I would like to change the content of the sidebar depending on the controller action, or the view. At the moment, in the views/layouts/main.php file, I have a sidebar defined as:

<div class="sidebar">hello!</div>

When the controller is image and the action is test, I would like to display this:

<div class="sidebar">Created at <? echo $image->created_at; ?></div>

The $image object is defined in the image controller and the test action.

In short, I would like to display a sidebar when the controller is image and the action is test, however, I would not like to have a different layout entirely. How can I accomplish this?


Solution

  • You can put a simple if-else check, using getController(), getAction() like this :

    if(Yii::app()->getController()->getId()=='image' && Yii::app()->getController()->getAction()->getId()=='test'){
        echo '<div class="sidebar">Created at '.$this->image->created_at.'</div>'; 
    }
    else
        echo '<div class="sidebar">hello!</div>';
    

    To access $image in a layout we need to make it a public property of the image controller itself, then in the action test where we initialize the $image, we will initialize the public $image, example:

     class ImageController extends Controller{
         public $image;
         ...
         public function actionTest(){
             $this->image=Example::model()->findByPk(1);// example
             ...
         }
     }
    

    This will allow us to access image in the layout albeit using $this->image->property.

    Also in the layout $this refers to the current controller, hence we can also use $this->id instead of Yii::app()->getController()->getId() to get the controller id(name which is image here) and $this->action instead of Yii::app()->getController()->getAction()->getId() to get the action id.