Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend Framework 2 - Layout and variable

i have a layout used by all my views and i need to assign a variable from a controller to this layout , if i use this method on a controller it doesn't work :

public function indexAction()
{
    return new ViewModel( array(
        'testvar' => 'bla',
    ));
}

anyone can help me ?

thanks

like image 874
Juck Avatar asked Nov 13 '12 11:11

Juck


4 Answers

There are three ways to achieve this in ZF2 (in your controller):

First:

$this->layout()->someVariableName = 'Some value for the variable';

Second:

$this->layout()->setVariable('someVariableName', 'Some value for the variable');

Third:

$this->layout()->setVariables(array(
    'someVariableName' => 'Some value for the variable',
    'anotherVariable'  => 'Some value for another variable',
);
like image 144
Josias Iquabius Avatar answered Oct 15 '22 14:10

Josias Iquabius


Rob Allen has posted a great article about how to access view variables in another view model (e.g.: layout)

Basically the following code, placed inside your layout.phtml, will match your needs:

<?php
$children = $this->viewModel()->getCurrent()->getChildren();
$child = $children[0];
?>
<!-- some HTML -->
<?php echo $this->escape($child->myvar);?>
like image 42
Sam Avatar answered Oct 15 '22 14:10

Sam


Have you tried:

$this->layout()->testvar = 'bla';

Using the layout controller plugin you can retrieve the ViewModel object that is used in layout.phtml.

like image 8
DrBeza Avatar answered Oct 15 '22 14:10

DrBeza


Because ZF2 ViewModel is tree structure, the layout actually is the root node of ViewModel, the ViewModel in your controller will be add as a child node of layout.

You could access layout ViewModel by access MvcEvent, try this in your controller:

public function indexAction()
{
    $events = $this->getServiceLocator()->get('Application')->getEventManager();
    $events->attach(MvcEvent::EVENT_RENDER, array($this, 'setVariableToLayout'), 100);
}

public function setVariableToLayout($event)
{
    $viewModel = $this->getEvent()->getViewModel();
    $viewModel->setVariables(array(
        'testvar' => 'bla',
    ));
}
like image 3
AlloVince Avatar answered Oct 15 '22 14:10

AlloVince