【问题标题】:Translations in Symfony 2.3 locale in request请求中的 Symfony 2.3 语言环境中的翻译
【发布时间】:2013-10-20 23:19:46
【问题描述】:

如何在 Symfony 2.3 中更改语言环境?

我创建了这个控制器:

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

刷新页面时不会显示更改。为什么?

【问题讨论】:

    标签: symfony symfony-2.3


    【解决方案1】:

    基于 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 }
    

    最后,你可以在你的控制器中使用:

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

    在这个link 你有一个非常相似的问题。

    【讨论】:

    • 可能与项目有关,但我必须将 KernelEvents::REQUEST => array(array('onKernelRequest', 17)) 设置为 16 -> KernelEvents::REQUEST => array(array('onKernelRequest', 16))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多