ZF2: Get module name (or route) in the application layout for menu highlight

前端 未结 3 1075
庸人自扰
庸人自扰 2021-01-13 01:19

How can I get in ZF2 the current (selected) module name in the application layout? Purpose: My application layout include the main menu of the zf2 app, and every time a modu

相关标签:
3条回答
  • 2021-01-13 01:30

    Use array_shift instead of array_pop (Kunal Dethe answer):

    $controller = $this->getParam('controller');
    $module_array = explode('\\', $controller);
    $module = array_shift($module_array);
    
    0 讨论(0)
  • 2021-01-13 01:45

    I know its too late to answer this question and also that there are a lot of answers available already but just in case someone views this question, it may be helpful.

    In the primary or any Module's 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 $CURRENT_MODULE_NAME variable in your layout file (as done in the question itself). The rest of the variables mentioned in the above code can be used if required.

    0 讨论(0)
  • 2021-01-13 01:48

    I prefer easier way without dealing with Module.php

    Place this code into layout.phtml

    $routeName = $this->getHelperPluginManager()->getServiceLocator()->get('Application')
                   ->getMvcEvent()->getRouteMatch()->getMatchedRouteName();
    if($routeName === "users") ...
    
    0 讨论(0)
提交回复
热议问题