How to access a variable of layout/main.php in view files

I have an variable in file protected/views/layouts/main.php which holds the count of table records. I am getting count right after the head tag in this file. Now i want to use this variable in my controller view files.

When i use the variable in view file its empty. I don’t want to fire query one more time for count i want to reuse the count variable.

Could some one help me out on this.

you should do it the other way round… view and layout files are not supposed to query the database. they are just for presentation.

you can find the count in the controller and that variable can be easily accessed in both your view files as well as main.php layout file

I could not able to do this way.

In my Site controller i have an action index where i have my variable and i could not able to access in main.php file




public function actionIndex()

{

      $categories=CHtml::listData(ImageCategories::model()->findAll(array('order' => 'name')), 'id', 'name');

      $this->render('index',array('categories'=>$categories));

}



I could not able to access $categories variable in main.php file is there some thing i missed over here

You should add a field to the controller, or use Yii registry

You cant pass something to the view and than access it in the layout

But if look in your code, you should create some view helper for this task…

For example a widget

To understand Why the variable you pass to the view is invisible in the layout you should look at the source code of render and understand the work flow

Read this http://www.yiiframework.com/wiki/249/understanding-the-view-rendering-flow/