简体   繁体   中英

Translating dynamic content in django templates

I have a html template rendered by a view in django. And the template has some dynamic values that the view sends.

Example::

{{ text_to_be_translated.brand_name}}

The above 'text_to_be_translated.brand_name' is a dictionary with thousands of keys like brand_name, which can hold many values like 'my brand', 'your brand' etc

I am not able to get the above dynamic text translated.

I tried to manually put msgids for the texts in the po file

msgid "my brand"
msgstr "カードインフォメーション"

But it doesn't get translated.

What am I doing wrong, please help.

Just writing so that somebody may benefit.

I solved the problem by writing a template filter and force translating the text in the template using 'django with tag'

In template.html

{% with card_details_trans=registration_card_details.card_details|template_trans %}
    {% trans card_details_trans %}
{% endwith %}

In Template Tag

@register.filter(name='template_trans')
def template_trans(text):
    try:
        return ugettext(text)
    except:
        return text

Logic

  1. Django doesn't know that contents of a dynamic variable needs to be translated.
  2. The with tag calculates the translated value from the applied filter and gives the translated output.

Hope it helps. Cheers!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM