Reputation:
I'm using zend MVC 3.1.1 and trying to pass variables from the called controller action to the layout but having real difficulties finding a way to do so. I haven't found a solution online for this problem.
Here is my base controller 'render' method that gets called to create the view model.
protected function render ( array $data = array () ) {
$controller = '';
$action = '';
$controller = strtolower( preg_replace( "/^(.*)\\\/", "", $controller ) );
$data[ 'controller' ] = $controller;
$data[ 'action' ] = $action;
$viewModel = new ViewModel( $data );
$viewModel->setTemplate( $controller . "/{$action}.php" );
return $viewModel;
}
And here is a snipped of my layout.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><!-- I WANT TO PUT VARIABLE HERE --></title>
</head>
<body>
<?=$this->content?>
</body>
</html>
How can I pass a variable from the controller 'render' action, or anywhere else in the execution, and have access to it in the same way I do to '$this->content'?
Thank you.
Upvotes: 0
Views: 1479
Reputation: 938
You can use a ViewModel
as the layout, on which you can set variables to make them available to the layout.
// [...]
$layoutModel = new ViewModel();
$layoutModel->setVariable('variable', 'value');
$viewModel->setLayout($layoutModel);
Upvotes: 0
Reputation: 1
In Zend 1.x you can set variable in controller like this
$this->view->layout()->isFlag = true;
and then catch it in layout
var_dump($this->layout()->isFlag); // true
Upvotes: -1
Reputation: 1227
Try
....
$viewModel = new ViewModel();
$viewModel->setVariables(
[
'controller' => $controller,
'action' => $action,
]
);
$viewModel->setTemplate( $controller . "/{$action}.php" );
return $viewModel;
...
You can find setVariables() method description inside vendor/zendframework/zend-view/src/Model/ViewModel.php
Upvotes: 0