How to pass variables to layout.phtml globally in ZF2?

前端 未结 6 1922
抹茶落季
抹茶落季 2020-12-05 07:21

I want to pass a series of variables to my layout.phtml throughout the whole application(globally). And by that I mean I don\'t wanna use

$this->layout()-         


        
6条回答
  •  Happy的楠姐
    2020-12-05 07:29

    You can pass global variable to your layout from Application/Module.php in ZendFramework 2 using ModuleManager as below:

    In your Application/Module.php

    Step 1:

    use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
    use Zend\ModuleManager\Feature\ConfigProviderInterface;
    use Zend\Mvc\MvcEvent;
    

    Step 2:

    class Module implements AutoloaderProviderInterface, ConfigProviderInterface
    {    
        public function onBootstrap(MvcEvent $e)
        { 
            $eventManager        = $e->getApplication()->getEventManager();
            $eventManager->attach('dispatch', array($this, 'loadConfiguration' ));
        }    
        public function loadConfiguration(MvcEvent $e)
        {           
              $controller = $e->getTarget();
              $controller->layout()->YOUR_VARIABLE_NAME = $YOUR_VALUE;
        }
    
    
      // Your remaining code here....
    
    }
    

    Step 3:

    In your layout.phtml file use your variable as $this->YOUR_VARIABLE_NAME

    I hope this helps.

提交回复
热议问题