【问题标题】:Translating formatted strings in Django not working在 Django 中翻译格式化的字符串不起作用
【发布时间】:2017-07-06 19:22:32
【问题描述】:

我在使用 django.utils.translations 翻译 Django 中的格式化字符串时遇到问题。只有没有格式的字符串(%s{})有效。

我的locale/en/LC_MESSAGES/django.po 文件:

msgid "foo"
msgstr "bar"

#, python-format
msgid "foo %s"
msgstr "bar %s"

#, python-format
msgid "foo %(baz)s"
msgstr "bar %(baz)s "

#, python-brace-format
msgid "foo {}"
msgstr "bar {}"

#, python-brace-format
msgid "foo {baz}"
msgstr "bar {baz}"

第一个字符串正在工作:

>>> from django.utils import translation
>>> translation.activate('en')
>>> translation.ugettext('foo')
'bar'

但休息不是:

>>> translation.ugettext('foo %s' % 'bax')
'foo bax'
>>> translation.ugettext('foo %(baz)s' % {'baz': 'bax'})
'foo bax'
>>> translation.ugettext('foo {}'.format('bax'))
'foo bax'
>>> translation.ugettext('foo {baz}'.format(baz='bax'))
'foo bax'

无论我使用 ugettext_lazygettext 还是 gettext_lazy - 相同的故事,不是翻译输出。

知道为什么格式化的字符串不起作用吗?

  • Django 1.11.3
  • Python 3.5.3

【问题讨论】:

    标签: django django-i18n


    【解决方案1】:

    您应该格式化 ugettext 返回的字符串,而不是调用中的字符串。请参阅下面的说明。

    代替:

    translation.ugettext('foo %s' % 'bax')
    translation.ugettext('foo %(baz)s' % {'baz': 'bax'})
    translation.ugettext('foo {}'.format('bax'))
    translation.ugettext('foo {baz}'.format(baz='bax'))
    

    你需要做的:

    translation.ugettext('foo %s') % 'bax'
    translation.ugettext('foo %(baz)s') % {'baz': 'bax'}
    translation.ugettext('foo {}').format('bax')
    translation.ugettext('foo {baz}').format(baz='bax')
    

    在您的代码中,您每次都尝试获取 'foo bax' 的翻译,而您的翻译文件中没有该 msgid。

    【讨论】:

    • 谢谢你。只见树木不见森林。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多