Cakephp - how to make error pages have its own layouts?

后端 未结 6 1379
被撕碎了的回忆
被撕碎了的回忆 2021-02-13 16:00

I wanna have a different layout for the page not found 404 page. How can i set a different layout for that page?

6条回答
  •  南方客
    南方客 (楼主)
    2021-02-13 16:24

    My solution for CakePHP 2.3

    Change the ExceptionRenderer in core.php to use your own renderer.

    app/Config/core.php:

    Configure::write('Exception', array(
      'handler' => 'ErrorHandler::handleException',
      'renderer' => 'MyExceptionRenderer',
      'log' => true
    ));
    

    app/Lib/Error/MyExceptionRenderer.php:

     App::uses('ExceptionRenderer', 'Error');
    
     class MyExceptionRenderer extends ExceptionRenderer 
     {
        /**
         * Overrided, to always use a bare controller.
         * 
         * @param Exception $exception The exception to get a controller for.
         * @return Controller
         */
        protected function _getController($exception) {
            if (!$request = Router::getRequest(true)) {
                $request = new CakeRequest();
            }
            $response = new CakeResponse(array('charset' => Configure::read('App.encoding')));
            $controller = new Controller($request, $response);
            $controller->viewPath = 'Errors';
            $controller->layout = 'error';
            return $controller;
        }
     }
    

    The advantage to this approach is that it ensures any exceptions thrown from AppController don't cause an endless loop when rendering the exception. Forces a basic rendering of the exception message every time.

提交回复
热议问题