0

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.

4
  • You can look at stackoverflow.com/questions/16665010/… Commented Oct 30, 2019 at 8:03
  • This does not work for me. I need to use the variable in the layout page, not the template / view and I need to pass it from the controller. This method allows me to access the variable in the view but not the layout that contains it. Commented Oct 30, 2019 at 22:53
  • Yes. I've tried that a number of times but the only variable that I have access to in the layout is $this->content. Doing a print_r even only shows $this->content as accessible variables. Commented Oct 31, 2019 at 11:48
  • 1
    You need to use a ViewHelper. Have a look at a good book on getting started with ZF3 Commented Nov 23, 2019 at 8:30

3 Answers 3

0

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

Sign up to request clarification or add additional context in comments.

1 Comment

Does not work. The variables are only then accessible in the template but not the layout. I need to set the variable(s) in the controller and have access to to it in the layout, that is, the page / PHP script that contains the view / template.
0

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); 

Comments

-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 

Comments