[英]Translating dynamic content in django
我有一個像這樣既有靜態部分又有動態部分的文本。
Custom message with %(card_status)s text inside
我正在確定翻譯文本的最佳方法是什么。
這是我目前所擁有的
{% blocktrans with obj.card_status as card_status %}Custom message with {{ card_status }} text inside{% endblocktrans %}
如果我這樣做,生成的消息是
msgid "Custom message with %(card_status)s text inside"
msgstr "This will be translated"
但是這種方法的問題在於,無論 card_status 變量是什么,翻譯的文本都是一樣的。
我嘗試使用 msgid 為每個 card_status 的可能值手動枚舉 django.po 文件。
但這沒有被考慮,例如,
msgid "Custom message with ACTIVE text inside"
msgstr "This will be translated with ACTIVE text"
有人可以建議可以在這里使用的方法或技巧。 我提到的堆棧中有許多類似的問題,但不知何故我無法獲得我需要的解決方案。
希望有人能一勞永逸地結束這個問題,讓大家開心。
為將來可能需要此功能的人回答此問題。
這更像是一種理解,而不是我創建的解決方案。
首先我有這個
{% blocktrans with obj.card_status as card_status %}Custom message with {{ card_status }} text inside{% endblocktrans %}
問題:部分 card_status 被替換為動態值,但沒有被翻譯。
解決方案:因此,我將名為template_trans的模板過濾器應用於計算值“ card_status ”,該值向 django 標記該變量也需要翻譯。 (將在下面添加該過濾器代碼)
{% blocktrans with obj.card_status|template_trans as card_status %}Custom message with {{ card_status }} text inside{% endblocktrans %}
現在執行makemessages命令會像以前一樣在po 文件中生成此文本
Custom message with %(card_status)s text inside
現在您需要手動將 card_status 可以采用的所有可能值添加到同一個po 文件中。 就像在我的情況下,我添加了這些值
msgid "ACTIVE"
msgstr ""
msgid "INACTIVE"
msgstr ""
msgid "LOST"
msgstr ""
現在 template_trans 的代碼在這里,添加它作為一個過濾器,你通常會有其他過濾器。
from django.utils.translation import ugettext
@register.filter(name='template_trans')
def template_trans(text):
try:
return ugettext(text)
except Exception, e:
return text
就是這樣,django 現在為您做了兩個翻譯,一個是使用上面發布的第一個 msgid 的靜態部分。 然后它根據實際值 ACTIVE 或 INACTIVE 等執行第二個操作,為您提供組合輸出。
注意 1:翻譯者應該在消息 id 中看到這個 %(variable_name)s 而不是 {{ variable_name }}。 這是通過使用 with 標記以及 blocktrans 和模板 trans 過濾器來歸檔的。 示例如上所示。
注意 2:您應該在 django.po 中填充 %(variable_name)s 的所有可能值。 如果不是,您將獲得變量的值而不是翻譯后的值。
注意 3:確保您在 po 文件中填充的各個值都填充了它們的 msgstr 部分...
Django提供了許多工具來本地化Python 代碼(主要通過gettext
和gettext_lazy
,包括復數)和模板(通過標簽trans
、 blocktrans
和plural
;甚至_()
在模板中可用)中的內容。
如果您發現 UI 中有未翻譯的文本,則需要通過上述機制公開該文本,而不是手動修改 PO 文件。
因此,如果您有一些狀態標志ACTIVE
、 INACTIVE
等,那么這顯然是需要以某種方式公開的特定於語言的內容。
一種方法是想象標志值對人類毫無意義——你會怎么做才能確保它們在 UI 中有意義? 確切地說:您將為它們分配字符串標簽,並且您將顯示這些字符串標簽而不是任何神秘的狀態值。
現在您只需要通過gettext
公開這些標簽就可以了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.