【问题标题】:(How) Can I use string substitution for working w/ Django’s i18n {% trans %} tag?(如何)我可以使用字符串替换来处理/ Django i18n {% trans %} 标签吗?
【发布时间】:2010-02-25 19:44:35
【问题描述】:

我正在寻找这样的东西:

{% trans "There are %{flowers}n flowers in the vase" < flowers:3 %}

现在显然语法是假的,但它应该足以证明我正在寻找什么。

我应该自己做饭吗?它看起来像一个常见的用例,所以我很惊讶快速网络搜索没有返回任何有用的信息。

我实际上开始讨厌使用 Django 模板系统...虽然我知道它旨在强制将应用程序逻辑与视图分离,但它通过侵入我的工作流程来做到这一点。我应该能够快速制作原型,并且只有在我需要与设计师合作时,我才应该对这样的事情更加严格。

【问题讨论】:

    标签: python django formatting templates internationalization


    【解决方案1】:

    我不确定您要做什么(< flowers:3 应该做什么?),但您看过blocktrans 吗?

    {% blocktrans count flowers|length as counter %}
        There is one flower in the vase.
    {% plural %}
        There are {{ counter }} flowers in the vase.
    {% endblocktrans %}
    

    【讨论】:

    • 等于 "... %s ..." % 替换.. 只是认为另一个 "%" 会模棱两可。现在当然 blocktrans 正是我所需要的。想不通我是怎么错过的?嗯,下次要小心点。感谢您的帮助!
    【解决方案2】:

    使用{% blocktrans %} 而不是{% trans %}

    【讨论】:

      【解决方案3】:

      您可能会发现模块 inflect.py 很有用,尽管这意味着离开模板系统。

      import inflect
      p = inflect.engine()
      p.num(numflowers, show=False)
      return 'There %s %s %s in the vase.' % (
                    p.pl('is'),
                    p.numwords(numflowers),
                    p.pl('flower'))
      

      与 numflowers = 1

      'There is one flower in the vase.'
      

      与 numflowers = 2

      'There are two flowers in the vase.'
      

      【讨论】:

        猜你喜欢
        • 2015-12-26
        • 1970-01-01
        • 2017-10-29
        • 2013-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-22
        相关资源
        最近更新 更多