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
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',
);
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);?>
Have you tried:
$this->layout()->testvar = 'bla';
Using the layout
controller plugin you can retrieve the ViewModel object that is used in layout.phtml
.
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',
));
}
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