如何将变量传递给 Zend Framework 2 中的错误视图脚本?

How to pass variables to the error view script in Zend Framework 2?

我捕获了框架特定的异常如下:

public function onBootstrap(MvcEvent $e)
{
    $eventManager = $e->getApplication()->getEventManager();
    $moduleRouteListener = new ModuleRouteListener();
    $moduleRouteListener->attach($eventManager);
    ...
    $sharedManager = $e->getApplication()
        ->getEventManager()
        ->getSharedManager();
    $sm = $e->getApplication()->getServiceManager();
    $sharedManager->attach('Zend\Mvc\Application', MvcEvent::EVENT_DISPATCH_ERROR, 
        function ($e) use($sm) {
            if ($e->getParam('exception')) {
                $sm->get('Logger')
                    ->crit($e->getParam('exception'));
            }
            // trying to pass a variable
            $e->getViewModel()->setVariable('foo', 'bar');
        });
}

然后当我尝试访问 /module/Application/view/error/index.phtml 中的 $foo 时,我得到 Notice: Undefined variable: foo.

如何将变量传递给错误查看脚本并在那里访问它?

它从 onBootstrap 内部将变量传递给布局。

试试这个:

$this->layout()->foo