Passing Data From The Controller To A View Using Layouts

Hi there, I’m new to Yii and this is my first post so be kind please! ;)

Couldn’t find a better and more clear topic title but the question is quite simple, is it possible to pass variables from a controller to a view if layouts are involved in the render?



When calling render() in the controller you pass all variables as an array in the second argument. They will be available in the view as variables with names matching keys from that array.

Now in the layout view file the contents of rendered view is available in the $contents variable.

I read the manual about passing variables to the view. The fact is that it doesn’t work for me. I can access controller’s properties with $this in the view though.

Even if I do:

$this->renderPartial(‘index’, array(“foo”=>“value”));

and in the view

x <?php echo($foo); exit;

It just renders the x as $foo is empty! (And as I used renderPartial no layout is involved!)

Any clue?



I suppose you’re talking about passing var to layout.

Passing variables to layout is kinda tricky, plz see this topic:

I use controller vars or clips, depending on my needs.

If you need your variables to be accessible only in view file, use $this->render(‘index’, array(‘foo’ => ‘bar’)) syntax.

If they’re still not available - look for errors in your code, something went wrong. Maybe a typo or something.

If you need vars to be accessible in partials that are rendered from inside the view file - you should pass them explicitly, for example:


$this->render(‘index’, array(‘foo’ => ‘bar’));


<h1>Here’s the view file</h1>

<? echo $foo; ?>

<? echo $this->renderPartial(’_partial’, array(‘foo’ => $foo)) ?>

Btw don’t use exit() in the view.