问题描述
在Python 2.7中使用格式
格式化字符串的新建议和推荐方法是否会在Django中导致非翻译字符串?
Does the new and recommended way to format strings available in Python 2.7 using format
result in a non translated string in Django?
字符串位于 .po
文件中,翻译后,不会在网站上翻译。例如:
The strings are in the .po
file, translated, but it won't be translated on the website. For example:
from django.utils.translation import ugettext as _
website_name = "Stackoverflow"
title = _(u"{sitename} is a good website".format(sitename=website_name))
翻译字符串后的 .po
文件如下所示:
The .po
file after translating the string looks like this:
#: path/to/file.py:4
msgid "{sitename} is a good website"
msgstr "{sitename} ist eine gute Website"
运行 django-admin.py compilemessages
并重新启动网络服务器后,处理的HTML页面仍然是英文,而所有其他字符串正在翻译。此外,虽然所有使用格式
的字符串未翻译,但使用%
运算符格式化的字符串将按预期转换。它也不是一个gettext / ugettext问题,因为这两个函数的问题是一样的。
After running django-admin.py compilemessages
and restarting the webserver, on the processed HTML page it is still in english, while all the other strings are being translated. Furthermore, while all strings using format
are not translated, strings formatted using the %
operator are translated as expected. It is also not a gettext/ugettext issue, as the problem is the same with both functions.
推荐答案
compilemessages
将字符串看作{sitename}是一个好的网站,但是当应用程序运行时,字符串实际上是MySite是一个很好的网站,当然没有翻译。您必须首先翻译裸字符串,然后然后可以对其执行模板操作。
compilemessages
sees the string as "{sitename} is a good website", but when the app is running the string is actually e.g. "MySite is a good website", which of course doesn't have a translation. You must translate the bare string first, and then you can perform template operations on it.
这篇关于字符串不会使用Python 2.7中提供的格式函数在Django中翻译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!