Symfony3 Language switch in Twig

3.4k views Asked by At

Gretings, I have a problem with changing languages from Twig template. My goal is to make it possible for user to switch page language according to his needs. I did everything according instruction: Making the Locale "Sticky" during a User's Session

My question is, how to change language, which is stored in session, from Twig template?

My best guess was:

{{ app.session.set('_lang', 'en') }}

But result was, that language change needed page to be refreshed twice to show results, one to set values in session, second to load page according language stored in session. Please advise!

2

There are 2 answers

0
JustinasT On BEST ANSWER

Solution was creating locale prefixes for all controllers and as malcolm offered, using route params:

{{ path(app.request.attributes.get('_route'), app.request.query.all|merge({'_locale': 'en'})) }}
0
Kaizoku Gambare On

This will allow you to get the route and the route's parameters without knowing them. Then it will override the _locale parameter with your value.

In Twig :

{{path(app.request.attributes.get('_route'),app.request.attributes.get('_route_params')|merge({'_locale': 'en'})) }}

With the HTML/Bootstrap code

<li class="nav-item dropdown">
    <a class="nav-link dropdown-toggle" id="language_switcher" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i class="fa fa-globe"></i></a>
    <div class="dropdown-menu" aria-labelledby="language_switcher">
        <a class="dropdown-item" href="{{ path(app.request.attributes.get('_route'),app.request.attributes.get('_route_params')|merge({'_locale': 'ru'})) }}"><span class="flag flag-ru"> </span>  Russian</a>
        <a class="dropdown-item" href="{{ path(app.request.attributes.get('_route'),app.request.attributes.get('_route_params')|merge({'_locale': 'en'})) }}"><span class="flag flag-us"> </span>  English</a>
    </div>
</li>