Zend Framework 2 - Layout and variable

前端 未结 6 804
醉梦人生
醉梦人生 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:04

    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',
        ));
    }
    

提交回复
热议问题