2
votes

I have a 404 error page set up through an event listener triggered by Kernel exceptions:

public function onKernelException(GetResponseForExceptionEvent $event)
{
    if ($event->isMasterRequest()) {
        $exception = $event->getException();

        if ($exception instanceof NotFoundHttpException) {
            $response = new Response();

            $event->setResponse(
                $response->setContent($this->templating->render(
                    'LandingPageBundle:Error:error404.html.twig',
                    ['welcome_url' => $this->router->generate("welcome")]
                ))
            );
        }
    }
}

kernel.kernel_exception_listener:
      class: S\Project\LandingPageBundle\EventListener\KernelExceptionListener
      arguments: [ "@router", "@logger", "@translator", @templating ]
      tags:
          - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }

This works, but when I try to use the trans filter on the twig error404.html.twig template, it does nothing. My locale is being set in a cookie and read by an event listener to Kernel Requests, so I tried adding the following to onKernelException:

$request = $event->getRequest();
$locale = $request->cookies->get('_locale');
$request->setLocale($locale);

After that, including {{ app.request.locale }} in the template displayed the correct locale, however, the trans filter does not seem to be picking this up.

It seems like my problem may be related to Symfony 2.1 set locale and yet that question does not quite fit my exact problem, and I'm not sure what can be done to fix the problem. Ideally my kernel request listener could trigger before the onKernelException, so that it would properly set the locale beforehand, but currently it seems that the kernel request event is not triggered during a 404. I took a look at http://symfony.com/doc/current/components/http_kernel/introduction.html to better understand Symfony's request sequence, but I'm not really clear on the sequence that happens in a bad request, but it looks like in the case of an exception, it skips most of the request flow and goes straight to the response, and as I recall from http://symfony.com/doc/current/book/translation.html#handling-the-user-s-locale

"Setting the locale using $request->setLocale() in the controller is too late to affect the translator. Either set the locale via a listener (like above), the URL (see next) or call setLocale() directly on the translator service."

Is there a way to use the trans filter on a twig templated 404 page?

1

1 Answers

2
votes

Try to inject the @translator and use its method setLocale.

['welcome_url' => $this->router->generate("welcome")]

And why did you create link in the listener? You should do it in the template using twig function called path.