Set layout variables for use by the (404) error pages in ZF2

喜夏-厌秋 提交于 2019-12-02 07:20:29

问题


At present I set a couple of variables to be used by the app's overall layout.phtml, using the onDispatch method of a BaseController, which all my other controllers extend:

public function onDispatch(MvcEvent $e) 
{

    $config = $this->getServiceLocator()->get('config');
    $this->layout()->setVariable('platformName', $config['platform']['name']);
    $this->layout()->setVariable('platformYear', $config['platform']['year']);
}

This works fine, until I test some error pages and find that these pages do not get provided with the variables, as it's not using the base controller.

How can I get around this problem and provide the error pages with the same variables?


回答1:


Change the event you're listening for.

In this case, I'd move this logic to the application bootstrap event or the application render event (I haven't tested this, but it would probably work fine).

One example, in your Module.php

public function onBootstrap($e)
{
    $config = $e->getApplication()->getServiceManager()->get('config');
    //$e->getViewModel()->setVariable();
}

Haven't tested that commented out line, but it should get you headed in the right direction.

EDIT: Found an example of using the render event

public function onBootstrap($e)
{
    $event = $e->getApplication()->getEventManager();

    $event->attach('render', function($e) {
        $config = $e->getApplication()->getServiceManager()->get('config');
        $e->getViewModel()->setVariable('test', 'test');
    });
} 



回答2:


(Necro)

When using onDispatch in a Controller, remember to return the parent with the event and all:

public function onDispatch(MvcEvent $e)
{
    // Your code
    return parent::onDispatch($e);
}

Otherwise, the logic on your Actions in that Controller will be ignored.



来源:https://stackoverflow.com/questions/18211279/set-layout-variables-for-use-by-the-404-error-pages-in-zf2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!