Using multiple languages in one template

Hey everyone,
I would like to use multiple translations in a single Django template. The idea is a translation app with fixed phrases where the user can pick his base and target language. My current workaround is to switch the language with the language tag on every new phrase but I was hoping for a cleaner solution. E.g.:

{% language eng %}
<td><p> {% translate "Bonjour, je suis" %} </p></td>
{% endlanguage %}
{% language fra %}
<td><p> {% translate "Bonjour, je suis" %} </p></td>
{% endlanguage %}

From what I’m reading in Switching language in templates, the parameter for language would typically be a string. ({% language 'en' %} instead of {% language en %}). This implies to me that it could be a variable that you iterate over to have Django generate those repeated segments.
I’m envisioning something like:

{% for lang in language_list %}
{% language lang %}
    <td><p>{% translate "Bonjour, je suis" %}</p></td>
{% endlanguage %}
{% endfor %}

If you’ve got a long list of supported languages, that might appear to be a little cleaner.

If this is something to be done a lot on a page (or set of pages), I might consider doing this type of work within a utility function and passing the set of translated phrases into the template through the context rather than having the templates perform the translation.

1 Like