在 django 中翻译动态内容

Pra*_*gam 5 django translation

我有一篇文本,既有静态部分又有动态部分,如下所示。

Custom message with %(card_status)s text inside

我正在确定翻译文本的最佳方法是什么。

这就是我目前所拥有的,

{% blocktrans with obj.card_status as card_status %}Custom message with {{ card_status }} text inside{% endblocktrans %}
Run Code Online (Sandbox Code Playgroud)

如果我这样做,生成的消息是

msgid "Custom message with %(card_status)s text inside"
msgstr "This will be translated"
Run Code Online (Sandbox Code Playgroud)

但这种方法的问题是,无论 card_status 变量是什么,翻译后的文本都是相同的。

我尝试使用 msgid 手动枚举 django.po 文件,了解每个 card_status 的可能值。

但这并没有被考虑,例如,

msgid "Custom message with ACTIVE text inside"
msgstr "This will be translated with ACTIVE text"
Run Code Online (Sandbox Code Playgroud)

有人可以建议一种可以在这里使用的方法或技巧吗?我提到的堆栈中有很多类似的问题,但不知何故我无法获得我需要的解决方案。

希望有人能够一劳永逸地结束这个问题,让每个人都高兴。

Pra*_*gam 4

为将来可能需要这个的人回答这个问题。

这更多的是一种理解,而不是我创建的解决方案。

首先我有这个

{% blocktrans with obj.card_status as card_status %}Custom message with {{ card_status }} text inside{% endblocktrans %}
Run Code Online (Sandbox Code Playgroud)

问题: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 %}
Run Code Online (Sandbox Code Playgroud)

现在执行makemessages命令会像以前一样在po 文件中生成此文本

Custom message with %(card_status)s text inside
Run Code Online (Sandbox Code Playgroud)

现在您需要手动将 card_status 可以采用的所有可能值添加到同一个po 文件中。就像我的例子一样,我添加了这些值

msgid "ACTIVE"
msgstr ""

msgid "INACTIVE"
msgstr ""

msgid "LOST"
msgstr ""
Run Code Online (Sandbox Code Playgroud)

现在 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
Run Code Online (Sandbox Code Playgroud)

就是这样,django 现在为你做了两个翻译,一个是使用上面发布的第一个 msgid 的静态部分。然后,它根据实际值 ACTIVE 或 INACTIVE 等执行第二个操作,为您提供组合输出。

注 1:译者应该在消息 id 中看到这个 %(variable_name)s,而不是 {{variable_name }}。这是通过使用 tag 以及 blocktrans 和 template trans 过滤器来实现的。示例如上所示。

注意 2:您应该在 django.po 中填充 %(variable_name)s 的所有可能值。如果没有,您将获得变量的值,而不是翻译后的值。

注意 3:确保您在 po 文件中填充的各个值都已填充其 msgstr 部分...