Symfony 3.0 - 不根据setLocale()进行翻译

时间:2016-05-23 20:06:30

标签: symfony

在我的config.yml中,如果有以下设置

parameters:
        locale: en
framework:
        translator:      { fallbacks: ["%locale%"] }

在我的控制器中,我将语言环境更改为法语:

$request->setLocale('fr')

当我想翻译Twig中的内容时{{ 'Something' | trans }}它没有用法语显示文字,即使在我看来这{{ dump(app.request.locale) }}给了我fr。 所以有些不对劲。

只有当我将config.yml中的语言环境更改为fr时才会这样:

parameters:
        locale: fr

然后我看到法文文本。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我最终创建了一个localeListener,它在控制器中设置语言环境时设置会话中的语言环境,如$request->setLocale('fr')。现在我的文本在相应的语言环境中被翻译,但仅在额外的页面刷新之后才开始。

namespace SiteBundle\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 after the default Locale listener
            KernelEvents::REQUEST => array(array('onKernelRequest', 15)),
        );
    }
}