设置供 ZF2 中的 (404) 错误页面使用的布局变量 [英] Set layout variables for use by the (404) error pages in ZF2

查看:19
本文介绍了设置供 ZF2 中的 (404) 错误页面使用的布局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我使用 BaseController 的 onDispatch 方法设置了几个要由应用程序的整体 layout.phtml 使用的变量,我的所有其他控制器都扩展了该方法:

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?

推荐答案

更改您正在侦听的事件.

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).

一个例子,在你的 Module.php 中

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.

找到使用渲染事件的示例

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

这篇关于设置供 ZF2 中的 (404) 错误页面使用的布局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆