Search code examples
symfonytwiglocalesymfony4

Translate locale symfony 4 twig template


I have a question about the translation of a twig template.

This is an actual way to translate.

{% trans into 'en_EN' %}Hello{% endtrans %}!,

Can I load directly the '' value from a database like this? (this returns an error).

{% trans into {{ app.user.lang }} %}Hello{% endtrans %}!,

or shall I use a controller to do it?

I'm now using the following function to translate:

{% with %}
{% set lang = app.user.lang %}
<button class="btn btn-outline-primary" type="button" data-toggle="dropdown">{% trans into lang %}Hello{% endtrans %}!, {{ app.user.username }}<i class="material-icons">arrow_drop_down</i></button>
{% endwith %}

But I'm not sure if is a good practice or not.


Solution

  • You don't need to use into, if you want to have translations based on the user's preferences, you add it through a listener or include the locale in the URL's, then all you have to do in your twig templates is {{ 'Hello' | trans }}

    See: https://symfony.com/doc/current/translation/locale.html