在symfony 2.0中自定义403错误页面

Joh*_*auß 4 http-status-code-403 symfony twig

我想在Symfony 2.0中自定义错误页面

我知道这是通过覆盖布局来完成的,app/Resources/TwigBundle/views/Exception/*但我想为不同的路由设置不同的错误页面.

我想要一个用于后端,一个用于前端.

我怎样才能做到这一点?

Mik*_*ike 10

你需要做的不是太难.Symfony允许您明确指定哪个控制器处理您的异常.因此,在config.yml中,您可以在twig配置下指定异常控制器:

从Symfony 2.2开始

twig:
   exception_controller:  my.twig.controller.exception:showAction

services:
    my.twig.controller.exception:
        class: AcmeDemoBundle\Controller\ExceptionController
        arguments: [@twig, %kernel.debug%]
Run Code Online (Sandbox Code Playgroud)

Symfony 2.1:

twig:
  exception_controller: AcmeDemoBundle\Controller\ExceptionController::showAction
Run Code Online (Sandbox Code Playgroud)

然后,您可以创建一个自定义showAction,根据路径显示自定义错误页面:

<?php
namespace AcmeDemoBundle\Controller;

use Symfony\Component\HttpKernel\Exception\FlattenException;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\TwigBundle\Controller\ExceptionController as BaseExceptionController;

class ExceptionController extends BaseExceptionController
{
    public function showAction(FlattenException $exception, DebugLoggerInterface $logger = null, $format = 'html')
    {
        if ($this->container->get('request')->get('_route') == "abcRoute") {
            $appTemplate = "backend";
        } else { 
            $appTemplate = "frontend";
        }

        $template = $this->container->get('kernel')->isDebug() ? 'exception' : 'error';
        $code = $exception->getStatusCode();

        return $this->container->get('templating')->renderResponse(
            'AcmeDemoBundle:Exception:' . $appTemplate . '_' . $template . '.html.twig',
            array(
                'status_code'    => $code,
                'status_text'    => Response::$statusTexts[$code],
                'exception'      => $exception,
                'logger'         => null,
                'currentContent' => '',
            )
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

显然你应该自定义if语句来测试当前路由以满足你的需求,但是这应该这样做.

如果没有创建特定的错误模板,您可能希望添加默认为正常Twig错误页面的代码.有关更多信息,请查看代码

Symfony\Bundle\TwigBundle\Controller\ExceptionController
Run Code Online (Sandbox Code Playgroud)

以及

Symfony\Component\HttpKernel\EventListener\ExceptionListener
Run Code Online (Sandbox Code Playgroud)