根据symfony 2.0中的路线自定义403错误页
我想自定义Symfony 2.0中的错误页面 我知道这是通过覆盖根据symfony 2.0中的路线自定义403错误页,symfony,twig,http-status-code-403,Symfony,Twig,Http Status Code 403,我想自定义Symfony 2.0中的错误页面 我知道这是通过覆盖app/Resources/TwigBundle/views/Exception/*中的布局来实现的,但我想为不同的路由设置不同的错误页面 我想要一个用于后端,一个用于前端 我怎样才能做到这一点呢?你需要做的事情并不太难。Symfony允许您显式指定哪个控制器处理您的异常。因此,在config.yml中,您可以在细枝配置下指定异常控制器: 自Symfony 2.2以来 twig: exception_controller:
app/Resources/TwigBundle/views/Exception/*
中的布局来实现的,但我想为不同的路由设置不同的错误页面
我想要一个用于后端,一个用于前端
我怎样才能做到这一点呢?你需要做的事情并不太难。Symfony允许您显式指定哪个控制器处理您的异常。因此,在config.yml中,您可以在细枝配置下指定异常控制器: 自Symfony 2.2以来
twig:
exception_controller: my.twig.controller.exception:showAction
services:
my.twig.controller.exception:
class: AcmeDemoBundle\Controller\ExceptionController
arguments: [@twig, %kernel.debug%]
至Symfony 2.1:
twig:
exception_controller: AcmeDemoBundle\Controller\ExceptionController::showAction
然后,您可以创建一个自定义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' => '',
)
);
}
}
以及
Symfony\Component\HttpKernel\EventListener\ExceptionListener
我用
参数:[“@twig”,“%kernel.debug%”]
而不是
参数:[@twig,%kernel.debug%]
感谢您的回复。工作起来很有魅力。
Symfony\Component\HttpKernel\EventListener\ExceptionListener