Set locale in Symfony 2.1

隐身守侯 提交于 2019-11-27 05:43:48

问题


I am trying to have a language switcher on my symfony 2.1 website.

I followed the official documentation, set the translation files but setting the locale with $request->setLocale('en_US'); doesn't seem to work. After some research, I found this question which provides a beginning of an answer with this listener technique.

However, I still don't manage to have it working, I'm not so sure about my listener declaration, is something wrong with it?

My controller:

public function englishAction(Request $request)
{
    $this->get('session')->set('_locale', 'en_US');
    return $this->redirect($request->headers->get('referer'));
}

Service declaration in config.yml:

services:
    my_listener:
        class:        "FK\MyWebsiteBundle\Listener\LocaleListener"

My routing:

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

回答1:


The declaration of the LocaleListener in yml (inspired by the current declaration of the new LocaleListener: \vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Resources\config\web.xml)

services:
    my_listener:
        class: "FK\MyWebsiteBundle\Listener\LocaleListener"
        arguments: [%locale%]
        tags:
            -  { name: kernel.event_subscriber }

Some snippets:

A language switcher in your template:

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

A redirection with locale change from a controller:

$LocalizedUrl = $this->get('router')->generate(
    $request->attributes->get('_route'), 
    ['_locale' => $locale] + $request->attributes->get('_route_params')
);

return new \Symfony\Component\HttpFoundation\RedirectResponse($LocalizedUrl);



回答2:


You should get the translator instance linked to your symfony kernel container:

$this->container->get('translator')->setLocale('fr');


来源:https://stackoverflow.com/questions/12951792/set-locale-in-symfony-2-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!