在Django中翻译格式化的字符串不起作用
问题描述:
我在使用django.utils.translations
翻译Django中的格式化字符串时遇到问题。只有没有格式的字符串(%s
或{}
)正在工作。在Django中翻译格式化的字符串不起作用
我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_lazy
,gettext
或gettext_lazy
母校 - 同样的故事,没有翻译输出。
任何想法为什么格式化的字符串不工作?
- 的Django 1.11.3
- 的Python 3.5.3
答
你应该格式化该呼叫是通过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你的翻译文件。
谢谢你。我看不到树林里的树林。 – Moritz