简体   繁体   English

翻译django模板中的动态内容

[英]Translating dynamic content in django templates

I have a html template rendered by a view in django. 我有一个由django中的视图呈现的html模板。 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 上面的'text_to_be_translated.brand_name'是一个包含brand_name等数千个键的字典,它可以包含许多值,如“我的品牌”,“您的品牌”等

I am not able to get the above dynamic text translated. 我无法将上述动态文本翻译过来。

I tried to manually put msgids for the texts in the po file 我试图在po文件中手动输入msgids文本

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' 我通过编写模板过滤器并使用'django with tag'强制翻译模板中的文本来解决问题

In template.html 在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. Django不知道需要翻译动态变量的内容。
  2. The with tag calculates the translated value from the applied filter and gives the translated output. with标签计算应用过滤器的转换值并给出转换后的输出。

Hope it helps. 希望能帮助到你。 Cheers!!! 干杯!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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