ZF2: get the module name (or route) in the application layout to highlight the menu

How can I get in ZF2 the current (selected) module name in the application layout? Purpose: in my application layout there is the main menu of the zf2 application, and every time a module is selected, I need to highlight the module menu voice. I also need to set the correct route (url, action) when this menu is created. Each module has a voice menu:

<ul class="nav"> <?php foreach ($menu_modules as $mod): $is_active = ($mod['name'] == $CURRENT_MODULE_NAME)?'selected':'';//GET MODULE NAME ?> <!-- class="active" --> <li><a href="#" <?php echo $is_active;?> ><?php echo $mod['title']; ?></a></li> <?php endforeach; ?> <li><a href="<?php echo $this->url('login/process', array('action'=>'logout')); ?>"><?php echo $this->translate('Logout') ?></a></li> </ul> <div class="row-fluid" id="main_container"> <?php echo $this->content; ?> </div> 
+6
source share
3 answers

I know that it is too late to answer this question, and also that there are many answers that already exist, but in case someone considers this question, it can be useful.

In the primary or any module Module.php write this -

 class Module { public function onBootstrap(MvcEvent $e) { $sm = $e->getApplication()->getServiceManager(); $router = $sm->get('router'); $request = $sm->get('request'); $matchedRoute = $router->match($request); $params = $matchedRoute->getParams(); $controller = $params['controller']; $action = $params['action']; $module_array = explode('\\', $controller); $module = array_pop($module_array); $route = $matchedRoute->getMatchedRouteName(); $e->getViewModel()->setVariables( array( 'CURRENT_MODULE_NAME' => $module, 'CURRENT_CONTROLLER_NAME' => $controller, 'CURRENT_ACTION_NAME' => $action, 'CURRENT_ROUTE_NAME' => $route, ) ); } } 

Then you can use the $CURRENT_MODULE_NAME variable in your layout file (as done in the question itself). The remaining variables mentioned in the code above can be used if required.

+8
source

I prefer a simpler way without dealing with Module.php

Put this code in layout.phtml

 $routeName = $this->getHelperPluginManager()->getServiceLocator()->get('Application') ->getMvcEvent()->getRouteMatch()->getMatchedRouteName(); if($routeName === "users") ... 
+2
source

Use array_shift instead of array_pop (Kunal Dethe answer):

 $controller = $this->getParam('controller'); $module_array = explode('\\', $controller); $module = array_shift($module_array); 
+1
source

All Articles