显示特定路由而不是错误页面 (404) - Symfony2 [英] Show a specific route instead of error page (404) - Symfony2

查看:29
本文介绍了显示特定路由而不是错误页面 (404) - Symfony2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想显示/sitemap 页面而不是错误页面/404.当然我不想要重定向,我仍然想要设置 404 HTTP 响应头.

Instead of an error page / 404 I want to just show the /sitemap page. Of course I don't want a redirect and I still want the 404 HTTP response header to be set.

这可能吗?我只能看到如何在 Twig 中设置模板.

Is this possible? All I can see is how to set templates in Twig.

我绝对不想要重定向.

推荐答案

Symfony Cookbook<中所示/a> 您可以通过两种方式覆盖错误页面:

As shown in the Symfony Cookbook you can override error pages in two ways:

  • 覆盖模板
  • 使用自定义异常控制器

如果您只想在 404 (HttpNotFoundException) 异常上显示 /sitemap 路由,您可以通过在 中创建一个新模板来覆盖 Twig 异常模板app/Resources/TwigBundle/views/Exception/error404.html.twig.

If you only want to show the /sitemap route on a 404 (HttpNotFoundException) exception you could override the Twig exception template by creating a new template in app/Resources/TwigBundle/views/Exception/error404.html.twig.

说明书中未显示的另一种方法是使用事件侦听器.当内核遇到异常时,一个kernel.exception 事件被调度.默认情况下,此异常由 Twig 提供的异常侦听捕获.你可以创建你自己的事件监听器来监听kernel.exception 事件并呈现页面:

Another way that is not shown in the cookbook is using an event listener. When the kernel encounters an exception, a kernel.exception event is dispatched. By default, this exception is caught by the exception listening provided by Twig. You can create your own event listener which listens for the kernel.exception event and renders a page:

<?php
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;

public function onKernelException(GetResponseForExceptionEvent $event)
{
    if ($event->getException() instanceof NotFoundHttpException) {
        $response = $this->templating->renderResponse(/* sitemap */);

        $event->setResponse($response)
    }
}

(我还没有测试过这段代码,所以你应该自己尝试一下!当然,你必须自己将模板服务注入到事件侦听器中).

(I haven't tested this code, so you should try it yourself! And you have to inject the templating service into the event listener yourself, of course).

这篇关于显示特定路由而不是错误页面 (404) - Symfony2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆