django translate variable content in template

Viewed 35250

I'm using {% trans %} template tag. Django docs say:

The {% trans %} template tag translates either a constant string (enclosed in single or double quotes) or variable content:

{% trans "This is the title." %} {% trans myvar %}

https://docs.djangoproject.com/en/4.0/topics/i18n/translation/#translate-template-tag

I found it impossible to do {% trans myvar %} because myvar simply doesn't show up in django.po file after running makemessages command.

Am I using it wrong? Could some help me with this?

9 Answers

make own tags

from django.utils.translation import ugettext as _

@register.simple_tag
def trans2(tr, *args, **kwargs):
    # print(':', kwargs)
    trans = _(tr)
    trans_str = trans.format(**kwargs)
    return trans_str

in template:

{% trans2 columns_once.res_data.message with value=columns_once.res_data.recommend%}

in django.po

#: default_content.py:136
msgid "_audit_recommend_speed"
msgstr "Рекомендованная скорость до {value} сек"

As one workaround, you can collect {% trans %}(django 3.0 and below) or {% translate %}(django 3.1 and above) tags between {% comment %} and {% endcomment %} in one template. This will save your efforts to repeat typing the same msgid should you have more than one language po file.

{% comment %}
{% trans "Tea" %}
{% trans "Clothes" %}
{% endcomment %.}

Make sure you run django-admin makemessages --all after putting the aforementioned code.

Related