0
votes

Django's default i18n system uses the code language (for instance, English) as translation keys; translations into other languages must be written from that base language. For instance, in a Django template, you would write {% trans "Hello" %} and then translate "Hello" into "Bonjour" or "Hola" in the French or Spanish translation file.

This has a major flaw: words that are spelled the same in English cannot be translated differently in other languages. For instance, if I use {% trans "Fire" %} in two places of my code, one of which meaning the thing that burns, and the other using a cannon, I would need "Feu" and "Tirer" respectively in French; but Django's i18n forces me to choose a single translation for "Fire".

The translation keys pattern solves this: I use translation keys such as {% trans "campsite.fire" %} and {% trans "cannon.fire" %} in my code, that I translate as "Fire" in an English translation file and as "Feu" and "Tirer" respectively in the French file.

Is this a supported use of Django's i18n system? How do I inject variables into such translations?

2
Django uses po files for the translations. Keys can be any matching string, or phrase. the example {% trans "cannon.fire" %} will work fine. - Michael Lindsay
How about if I need to inject a variable in the translation? It looks like it needs to "appear" in the key in order to be available to the translation. - foucdeg

2 Answers

0
votes

The current (yet awkward) way I've made it work is:

  • using translation keys such as {% trans "cannon.fire" %}

  • if I need to use a variable, use a translation key followed by a variable:

    {% blocktrans %}email.password_reset.click_link {{link}}{% endblocktrans %}

    Then in my translations I can use the link variable as %(link)s

It feels like an unintended use, very different from the doc. There may be a more official way to do this.

0
votes

Yes this is possible. Keys can be any matching string, or phrase.

template.html

{% trans "cannon.fire" %} 
{% trans "campsite.fire" %} 

po file:

msgid "cannon.fire"
msgstr "Tirer"

msgid "campsite.fire"
msgstr "Feu"

For varibles in the translation, there is blocktranslate tag that allows variables in the translation.

{% blocktranslate %} hello my name is {{ name }} {% endblocktranslate %}

Translation of variables in the render context is also possible:

{% translate myvar %}