In my ZF2 application I have a this navigation view script:
$routeMatch = $this->getHelperPluginManager()
->getServiceLocator()
->get('Application')
->getMvcEvent()
->getRouteMatch();
$currentRoute = $routeMatch instanceof \Zend\Mvc\Router\RouteMatch ? $routeMatch->getMatchedRouteName() : null;
?>
<?php foreach ($this->container as $page) : ?>
<li <?php echo $currentRoute == $page->getRoute() ? ' class="active"' : null;?>>
<?php echo $this->navigation()->menu()->htmlify($page, true, false) . PHP_EOL; ?>
</li>
<?php endforeach; ?>
Since the getServiceLocator()
is now deprecated, I need another way to get the information about the current route into the navigation view script.
This view script gets set as partial and called in the layout.phtml
:
echo $this->navigation('navigation')->menu()->setPartial('navigation/default');
So I got the idea to pass the need information via a template variable. I created one in the Module#onDispatch(...)
:
public function onDispatch(MvcEvent $mvcEvent)
{
$viewModel = $mvcEvent->getApplication()->getMvcEvent()->getViewModel();
$routeMatch = $mvcEvent->getRouteMatch();
$viewModel->currentRoute = $routeMatch instanceof RouteMatch
? $routeMatch->getMatchedRouteName() : null
;
}
Now I can access it in the layout.phtml
. But I don't find a way to pass it into the navigation view script, since the Zend\View\Helper\Navigation\Menu#setPartial(...)
` doesn's accept any arguments for variables.
How to pass variables (especially the information about the current route) into the navigation view in Zend Framework 3?