404页面在我们平常浏览网页的时候并不会经常碰到,也因此很容易被忽略,在Zend Framework 2中,项目的结构已经默认提供了404 页面,包括样式等等。但是有时,我们需要定制符合自己网站的404 页面样式时,该怎么办呢?
其实非常简单,编辑错误页面的layout ,例如errorlayout
module.config.php
'view_manager' => array ( 'display_not_found_reason' => true, 'display_exceptions' => true, 'doctype' => 'HTML5', 'not_found_template' => 'error/404', 'exception_template' => 'error/index', 'template_path_stack' => array ( __DIR__ . '/../view' ), 'template_map' => array ( 'error/404' => __DIR__ . '/../view/error/404.phtml', 'error/index' => __DIR__ . '/../view/error/index.phtml', 'error/layout'=> __DIR__ . '/../view/layout/error_layout.phtml' ) ),
module.php
class Module{ public function onBootstrap(MvcEvent $e) { $e->getApplication()->getServiceManager()->get('translator'); $eventManager = $e->getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR,array($this,'onDispatchError'),100); } function onDispatchError(MvcEvent $e) { $vm = $e->getViewModel(); $vm->setTemplate('error/layout'); }}
这个方式,解决由于路由问题导致的错误。
如果在controller > action 中进入错误页面,则非常简单,调用下面的方法:
$this->notFoundAction();