Set locale in Symfony 2.1

后端 未结 2 1019
眼角桃花
眼角桃花 2020-12-09 01:01

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 $requ

相关标签:
2条回答
  • 2020-12-09 01:06

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

    $this->container->get('translator')->setLocale('fr');
    
    0 讨论(0)
  • 2020-12-09 01:22

    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);
    
    0 讨论(0)
提交回复
热议问题