本文介绍了Symfony 2.1设置区域设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何在Symfony2.1中设置语言环境吗?

Does anybody know how to set the locale in Symfony2.1?

我正在尝试:

$this->get('session')->set('_locale', 'en_US');

$this->get('request')->setLocale('en_US');

但是这些都不起作用,devbar告诉我:

but none of those has any effect, the devbar tells me:

无论如何,始终使用config.yml中定义的后备区域设置

Anyway, it is always the fallback locale that is used, as defined in config.yml

(PS:我试图按照此处

推荐答案

即使Symfony 2.1指出您可以通过Request或Session对象简单地设置语言环境,但我从未设法使其起作用,设置语言环境只是没有效果.

Even though the Symfony 2.1 states that you can simply set the locale via the Request or Session objects, I never managed to have it working, setting the locale simply has no effect.

因此,我最终使用了侦听器和细枝路由来处理语言环境/语言:

So I ended up using a listener coupled with twig routing to handle the locale/language:

听众:

namespace FK\MyWebsiteBundle\Listener;

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;
        }

        if ($locale = $request->attributes->get('_locale')) {
            $request->getSession()->set('_locale', $locale);
        } else {
            $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
        }
    }

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

在service.xml中注册侦听器:

Register the listener in service.xml:

<service id="fk.my.listener" class="FK\MyWebsiteBundle\Listener\LocaleListener">
    <argument>%locale%</argument>
    <tag name="kernel.event_subscriber"/>
</service>

路由必须如下所示:

homepage:
pattern:  /{_locale}
defaults: { _controller: FKMyWebsiteBundle:Default:index, _locale: en }
requirements:
    _locale: en|fr|zh

并通过以下方式处理路由:

And handle the routing with:

{% for locale in ['en', 'fr', 'zh'] %}
    <a href="{{ path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale' : locale})) }}">
{% endfor %}

这样,当您单击链接以更改语言时,将自动设置区域设置.

This way, the locale will automatically be set when you click on a link to change the language.

这篇关于Symfony 2.1设置区域设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:07