Zend Framework 2 - Layout and variable

前端 未结 6 801
醉梦人生
醉梦人生 2021-01-31 04:50

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 :

p         


        
6条回答
  •  情歌与酒
    2021-01-31 05:06

    See the add View Variable section below

    add it in your module.php file.

    You can also do this using view helper.

    /**
         * Remember to keep the init() method as lightweight as possible
         * 
         * @param \Zend\ModuleManager\ModuleManager $moduleManager
         */
        public function init(ModuleManager $moduleManager) 
        {        
            $events = $moduleManager->getEventManager();
            $events->attach('loadModules.post', array($this, 'modulesLoaded'));
            $events->attach('onBootstrap', array($this, 'bootstrap'));
    
            $sharedEvents = $events->getSharedManager();
            $sharedEvents->attach(__NAMESPACE__, 'bootstrap', array($this, 'bootstrap'), 100);
            $sharedEvents->attach(__NAMESPACE__, 'bootstrap', array($this, 'initializeView'), 100);
            $sharedEvents->attach(__NAMESPACE__, 'dispatch', array($this, 'addViewVariables'), 201);        
        }
    
    
    /**
     * 
     * @param \Zend\Mvc\MvcEvent $e
     */
    public function loadConfiguration(MvcEvent $e) 
    {        
        $e->getApplication()->getServiceManager()
                ->get('ControllerPluginManager')->get('AclPlugin')
                ->checkAcl($e); //Auth/src/Auth/Controller/AclPlugin      
    }
    
    /**
     * 
     * @param \Zend\EventManager\EventInterface $e
     */
    public function bootstrap(Event $e) {
    
        $eventManager = $e->getParam('application')->getEventManager();
        //$app->getEventManager()->attach('dispatch', array($this, 'checkAcl'), 100);
    }
    
    /**
     * pass variables to layout
     * 
     * @param \Zend\EventManager\EventInterface $e
     */
    public function addViewVariables(Event $e) 
    {
        $route = $e->getRouteMatch();
        $viewModel = $e->getViewModel();
        $variables = $viewModel->getVariables();
        if (false === isset($variables['controller'])) {
            $viewModel->setVariable('controller', $route->getParam('controller'));
        }
        if (false === isset($variables['action'])) {
            $viewModel->setVariable('action', $route->getParam('action'));
        }
    
        $viewModel->setVariable('module', strtolower(__NAMESPACE__));        
    }
    
    /**
     * 
     * @param \Zend\Mvc\MvcEvent $e
     */
    public function initializeView(Event $e) 
    {
    
    }
    

    and in your layout you can simply access those variables using their name such as $module, $action, $controller according to above example

提交回复
热议问题