Search code examples
phplayoutzend-frameworkzend-framework3zf3

How to change layout for the error pages configured in modules.config?


I´m using ZF3 and I need to change the layout of my error pages. They are called by the following configuration in Application modules.config file:

   'view_manager' => [
        'display_not_found_reason' => true,
        'display_exceptions'       => true,
        'doctype'                  => 'HTML5',
        'not_found_template'       => 'error/404',
        'exception_template'       => 'error/index',
        'template_map' => [
            'layout/layout'           => __DIR__ . '/../view/layout/layout.phtml',
            'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
            'error/404'               => __DIR__ . '/../view/error/404.phtml',
            'error/index'             => __DIR__ . '/../view/error/index.phtml',
        ],
        'template_path_stack' => [
            __DIR__ . '/../view',
        ],
    ],

How can I set a specific layout for 404.phtml and index.phtml pages ?


Solution

  • If you want a specific layout for a specific action, you can use in a controller:

    $this->layout()->setTemplate('layout/anOtherLayout');
    

    If you want all the actions of your controller have the same layout, your controller can inherits AbstractActionController and override its onDispatch() method:

    class IndexController extends AbstractActionController 
    {
        public function onDispatch(MvcEvent $e) 
        {
            // Call the base class onDispatch() first and grab the response
            $response = parent::onDispatch($e);        
    
            $this->layout()->setTemplate('layout/layout2');                
            // Return the response
            return $response;
        }
    }
    

    The same logic can be used in your Module.php where you can check if the route exists (404) and set a specific layout if not.