ZF2 - How to change the error/404 response page? Not just template but to set a new ViewModel

前端 未结 7 2437
离开以前
离开以前 2021-01-05 22:46

By default the page is set like this in the Application module.config array:

\'template_map\' => array(
    \'error/404\' => __DIR__ . \'/         


        
7条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-05 23:38

    There is another way. To catch an EVENT_DISPATCH_ERROR and totally rebuild viewModel. Cavern is that layout – is a root viewModel, and content appended into layout by default is another viewModel (child). These points are not such clear described in official docs.

    Here is how it can look like in your Module.php:

    public function onBootstrap(MvcEvent $event)
    {
        $app = $event->getParam( 'application' );
        $eventManager = $app->getEventManager();
    
    
        /** attach Front layout for 404 errors */
        $eventManager->attach( MvcEvent::EVENT_DISPATCH_ERROR, function( MvcEvent $event ){
    
            /** here you can retrieve anything from your serviceManager */
            $serviceManager = $event->getApplication()->getServiceManager();
            $someVar = $serviceManager->get( 'Some\Factory' )->getSomeValue();
    
            /** here you redefine layout used to publish an error */
            $layout = $serviceManager->get( 'viewManager' )->getViewModel();
            $layout->setTemplate( 'layout/start' );
    
            /** here you redefine template used to the error exactly and pass custom variable into ViewModel */
            $viewModel = $event->getViewModel();
            $viewModel->setVariables( array( 'someVar' => $someVar ) )
                      ->setTemplate( 'error/404' );
        });
    }
    

提交回复
热议问题