gpt4 book ai didi

symfony - 根据symfony 2.0中的路线自定义403错误页面

转载 作者:行者123 更新时间:2023-12-02 10:41:44 25 4
gpt4 key购买 nike

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

我知道这是通过覆盖 app/Resources/TwigBundle/views/Exception/* 中的布局来完成的,但我希望针对不同的路线有不同的错误页面。

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

我怎样才能实现这个目标?

最佳答案

您需要做的事情并不太难。 Symfony 允许您显式指定哪个 Controller 处理您的异常。因此,在 config.yml 中,您可以在 twig 配置下指定异常 Controller :

自 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' => '',
)
);
}
}

显然,您应该自定义 if 语句,它会在其中测试当前路由以满足您的需求,但这应该可以做到。

如果您没有创建特定的错误模板,您可能需要添加默认到正常 Twig 错误页面的代码。欲了解更多信息,请查看

中的代码
Symfony\Bundle\TwigBundle\Controller\ExceptionController

以及

Symfony\Component\HttpKernel\EventListener\ExceptionListener

关于symfony - 根据symfony 2.0中的路线自定义403错误页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14282690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com