4

ウェブサイトの言語を変更した後、ユーザーをリダイレクトするためにコントローラーを使用しています。

return $this->redirect($this->generateUrl($_redirectTo), 301);

問題は、「/path/ にリダイレクトしています」というメッセージが表示されることです。これは望ましくありません。そのメッセージを変更することは可能ですか?

4

1 に答える 1

13

メソッドController::redirect()は実際には、新しいRedirectResponseオブジェクトを作成しています。
デフォルトのテンプレートは応答にハードコーディングされていますが、いくつかの回避策があります。

この例では、TWIG テンプレートを使用するため、@templatingサービスが必要ですが、ページをレンダリングするために必要なものは何でも使用できます。

まず、必要なコンテンツを含むテンプレート301.html.twigをに作成します。Acme/FooBundle/Resources/views/Error/

@AcmeFooBundle/Resources/views/Error/301.html.twig

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="refresh" content="1;url={{ uri }}" />
    </head>
    <body>
        You are about to be redirected to {{ uri }}
    </body>
</html>

イベントリスナーから

このテンプレートをグローバルにしたい場合はRedirectResponse、応答をリッスンし、指定された応答がのインスタンスであるかどうかを確認するイベントリスナーを作成できます。RedirectResponse
これは、コントローラーで引き続き使用できることを意味しますreturn $this->redirect。応答のコンテンツのみが影響を受ける。

services.yml

services:
    acme.redirect_listener:
        class: Acme\FooBundle\Listener\RedirectListener
        arguments: [ @templating ]
        tags:
            -
                name: kernel.event_listener
                event: kernel.response
                method: onKernelResponse

Acme\FooBundle\Listener\RedirectListener

use Symfony\Component\Templating\EngineInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;

class RedirectListener
{
    protected $templating;

    public function __construct(EngineInterface $templating)
    {
        $this->templating = $templating;
    }

    public function onKernelResponse(FilterResponseEvent $event)
    {
        $response = $event->getResponse();

        if (!($response instanceof RedirectResponse)) {
            return;
        }

        $uri  = $response->getTargetUrl();
        $html = $this->templating->render(
            'AcmeFooBundle:Error:301.html.twig',
            array('uri' => $uri)
        );

        $response->setContent($html);
    }
}

コントローラーから

テンプレートをアクションから直接変更する場合は、これを使用します。
変更は、アプリケーション全体ではなく、指定されたアクションでのみ使用できます。

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

class FooController extends Controller
{
    public function fooAction()
    {
        $uri = $this->generateUrl($_redirectTo);

        $response = new RedirectResponse($uri, 301);
        $response->setContent($this->render(
            'AcmeFooBundle:Error:301.html.twig',
            array( 'uri' => $uri )
        ));

        return $response;
    }
}
于 2013-08-13T09:41:08.437 に答える