I would add some links to differents locales versions in my existing website. It works quite well but it is pretty ugly^^
<li>
<a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge(app.request.query.all|merge({_locale: 'es'}))) }}">
<img src="{{ asset('img/flags/es.jpg') }}" alt="es">
</a>
</li>
<li>
<a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge(app.request.query.all|merge({_locale: 'fr'}))) }}">
<img src="{{ asset('img/flags/fr.jpg') }}" alt="fr">
</a>
</li>
Do you have an idea for doing it better ?
If you want to create a link to a internal page in a Twig template, and there's not already a variable in the template that contains the URL you want to link to, you'll need to determine the route of the thing you want to link to and then use the Twig url() or path() functions to generate appropriate URLs.
Twig Extensions Defined by Symfony¶. Twig is the template engine used in Symfony applications. There are tens of default filters and functions defined by Twig, but Symfony also defines some filters, functions and tags to integrate the various Symfony components with Twig templates. This article explains them all.
A better policy is to include the locale in the URL using the special _locale parameter: When using the special _locale parameter in a route, the matched locale is automatically set on the Request and can be retrieved via the getLocale () method.
To set the user's locale, you may want to create a custom event listener so that it's set before any other parts of the system (i.e. the translator) need it: The custom listener must be called before LocaleListener, which initializes the locale based on the current request.
You may need this in many pages and/or more than one project. Here's a possible way based on what I've been using in some:
# app/config/config.yml
# ...
parameters:
# ...
app_locales: [en, es, fr]
twig:
# ...
globals:
locales: %app_locales%
# ...
Then a template for holding flags:
{# app/Resources/views/includes/_flags.html.twig #}
{% set route = app.request.attributes.get('_route') %}
{% set route_params = app.request.attributes.get('_route_params') %}
{% set params = route_params|merge(app.request.query.all) %}
{# You may want to not print a flag/link for current view, the "if" here let you handle it #}
{% for locale in locales if locale != app.request.locale %}
<li>
<a href="{{ path(route, params|merge({ _locale: locale })) }}">
<img src="{{ asset('img/flags/' ~ locale ~ '.jpg') }}" alt="{{ locale }}">
</a>
</li>
{% endfor %}
Finally include flags in any view:
{# app/Resources/views/base.html.twig #}
{% include 'includes/_flags.html.twig' %}
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