I want to send a parameter from controller to layout (i.e. main.php). But I am not able to get the param in main.php
I tried:
Controller Code:
$this->render('index',array('param' => $paramValue));
And this is how i was trying to get this in layout ie. main.php
$this->param
(as in yii 1)$param
But i am not able to get param value in layout. Can anyone tell me how to do this?
yii\base\View has special $params property.
For example it's used for building breadcrumbs in default generated CRUD code templates with Gii.
You can set it like this before rendering:
use Yii;
Yii::$app->view->params['customParam'] = 'customValue';
Inside a controller you can set it like this:
$this->view->params['customParam'] = 'customValue';
Then it will be available in views (including main layout):
/* @var $this yii\web\View */
echo $this->params['customParam'];
You can also find it in official guide.
I would like to suggest you some steps for this problem.
Check For parameter and If exist then use it.
//in controller method
$this->render("view-file-name",["paramName" => "some parameter"]);
//in view file for eg: index.php
//i'm passing paremeter sent form controller's action to view params.
$this->params["paramFromViewFile"] = $paramName; //here $paramName is the parameter we sent from controller's method
//access parameter sent from view file
if($this->params && !empty($this->params["paramFromViewFile"]))
{
echo $this->params["paramFromViewFile"];
}
In Yii2 you can access your controller object from a view using $this->context
for example if in your controller you set a parameter like this:
public $title = 'My custom title';
Then in your layout you can read it like this:
$this->context->title
It is explained in Yii documentation in section: Accessing Data in Views
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