I use twig for templating in a multilingual Symfony2 project. There is a language switcher in layout.html.twig
I want the user can switch languages without changing the current page by clicking the language link. I have written the following code which just does duty for static pages. Since the language links just pass locale
to the route, in case of involvement of additional required parameters, it obviously throws the exception: route has some missing mandatory parameters
<ul id="lang">
<li><a href="{{ path(app.request.attributes.get('_route'), {_locale: 'az'}) }}">AZ</a></li>
<li><a href="{{ path(app.request.attributes.get('_route'), {_locale: 'en'}) }}">EN</a></li>
</ul>
You can get the route parameters with .get('_route_params')
and merge them with your desired locale:
<ul class="lang-menu">
<li><a href="{{ path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale': 'ca'})) }}">Català</a></li>
<li><a href="{{ path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale': 'en'}))}}">English</a></li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With