-->

Translations in Symfony 2.3 locale in request

2019-01-20 12:53发布

问题:

How can I change locale in Symfony 2.3 ?

I created this controller:

public function changelocaleAction($lang)
{
    $request = $this->get('request');
    $request->setLocale($lang);
    return $this->redirect($request->headers->get('referer'));
}

It doesn't show changes when the page is refreshed. Why?

回答1:

Based on Symfony2 documentation:

namespace Acme\LocaleBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class LocaleListener implements EventSubscriberInterface
{
    private $defaultLocale;

    public function __construct($defaultLocale = 'en')
    {
        $this->defaultLocale = $defaultLocale;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        if (!$request->hasPreviousSession()) {
            return;
        }

        // try to see if the locale has been set as a _locale routing parameter
        if ($locale = $request->attributes->get('_locale')) {
            $request->getSession()->set('_locale', $locale);
        } else {
            // if no explicit locale has been set on this request, use one from the session
            $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
        }
    }

    public static function getSubscribedEvents()
    {
        return array(
            // must be registered before the default Locale listener
            KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
        );
    }
}

services.yml

services:
    acme_locale.locale_listener:
        class: Acme\LocaleBundle\EventListener\LocaleListener
        arguments: ["%kernel.default_locale%"]
        tags:
            - { name: kernel.event_subscriber }

Finally, you can use in your controller:

$locale = $this->getRequest()->getLocale();

In this link you have a very similar question.