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?
From your controller you can do something like this:
and access the variables from your view like this:
and here is your answer; you can access these same variables from the layout like this:
in controller pass the variable, then in VIEW (not layout yet) create
Now in layout you can access whole array with just
Hope this helps you.
Alternatively, you could add a property in the Controller such as
And then output it in the layout (//layouts/column2)
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:
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
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:
and in the layout:
(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".