Reputation: 61138
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?
Upvotes: 12
Views: 20446
Reputation: 2865
After sets of debugging in Yii2 I found out that the only variables (excluding global variables) that are accessible inside of a layout file are _file_ (path to current layout file) and _params_ (an array containing variable content that is a HTML output bufferized from a file passed for rendering from a controller).
Except answers provided by @ldg (which I consider as most useful and informative, but resource spending) and @Petra Barus.
I also came out with a good solution of dividing layout into explicit files and calling them inside of a rendered file:
echo $this->renderPhpFile(Yii::getAlias('@app/views/layouts/somelayout.php'), [
'var' => $variableThatIsAccessibleInRenderedFile,
]);
Upvotes: 0
Reputation: 81
in controller pass the variable, then in VIEW (not layout yet) create
$this->params['myvar'] = 'hello';
Now in layout you can access whole array with just
echo $this->params['myvar'];
Hope this helps you.
Upvotes: 4
Reputation: 133
From your controller you can do something like this:
$this->render('/mail/registration',array('url'=>$url, 'description'=>'some description'));
and access the variables from your view like this:
<h3><?php echo $url; ?></h3>
and here is your answer; you can access these same variables from the layout like this:
<h3><?php echo $data['url']; ?></h3>
Upvotes: -2
Reputation: 4013
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 : '';
Upvotes: 15
Reputation: 9402
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".
Upvotes: 7