How To Add Sidebar In All Controller Actions

So you want to add a [size="3"]sidebar for all views[/size]

in a certain controller example "user".

This has been annoying me for months, so I’ve decided to write a tutorial how to do it simple in Yii2.

  1. Update Your Layout File To Handle 2 Columns on bootstrap. Add



$this->params['sideBar']!='';







<?php $this->beginContent('@app/views/layouts/main.php'); ?>


<div class="row">

   <div class="col-md-3">

    <div class="pg-sidebar">          

      <?php 

		if(@$this->params['sideBar']!='') 

			echo $this->params['sideBar'];  

	  

	  ?>


      <?= $this->blocks['toolbar']; ?>

    </div>      

  </div>

  <div class="col-md-9">

    <?= $content; ?>

  </div>

</div>


<?php $this->endContent(); ?>




  1. Update your action to use this new layout. Test it to see hello.



	public function actionAccount() {

		$this->layout = "/column2";    <----- 

		Yii::$app->view->params['sideBar'] = 'hello';

		

		return $this->render('account');

	}



  1. Using the special variable of “Yii::$app->view->params[‘sideBar’]”

we can now set it to anything.

Use a simple render to change it to whatever sidebar you want. Put True behind to echo the return as a string.

In Controller




Yii::$app->view->params['sideBar'] = $this->renderPartial('partials/_profile', ['name'=>'value'],true);




  1. If you want it to appear for all action, just add it to before action or in the module section.