I know how to pass variable from controller into a view:
$this->render('view_name', array('variable_name'=>'variable_value'));
however I'd like to pass some variables to layout. The only connection between controller and layout seems to be the public $layout attribute in controller class, like this:
public $layout='//layouts/column2';
However, I do not see a way to pass a variable to it?
It doesn't really seem to be set up to do that easily from what I can tell, so if you are relying on it to pass a lot of data, you might want to think of a different way to set up your application.
A couple ways that you could do it are to use the Yii params via
Yii::app()->params['myvar'] = $mixed;
which you can set in the controller and access in the layout. Otherwise you can use regular PHP global vars, with all the issues that approach entails.
In your controller you would do something like:
global $testvar;
$testvar = 'hello';
and in the layout:
echo $GLOBALS['testvar'];
(Even if it's not in a function, you still need to retrieve it via GLOBALS.)
You could pass an object this way for more structured data, but you are still using a global var. Another, possibly even less desirable method, would be via a session var, e.g., Yii::app()->session['myvar']
or a Yii "flash message".
Alternatively, you could add a property in the Controller such as
class SiteController extends CController {
public $myvar;
//...
And then output it in the layout (//layouts/column2)
echo isset($this->myvar) ? $this->myvar : '';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With