Translations in Symfony 2.3 locale in request

后端 未结 1 911
生来不讨喜
生来不讨喜 2020-12-11 23:45

How can I change locale in Symfony 2.3 ?

I created this controller:

public function changelocaleAction($lang)
{
    $request = $this->get(\'reques         


        
相关标签:
1条回答
  • 2020-12-12 00:33

    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.

    0 讨论(0)
提交回复
热议问题