Strings won't be translated in Django using format function available in Python 2.7

一曲冷凌霜 提交于 2020-01-01 07:37:49

问题


Does the new and recommended way to format strings available in Python 2.7 using format result in a non translated string in Django?

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))

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"

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.


回答1:


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.




回答2:


i had the same problem so i translated the text first and then added the dynamic content like

title = _(u"is a good website")
title = " ".join([website_name, title])

There must be a better way to do this




回答3:


The following should work:

_('Foo %(x)s') % {'x': "bar"}

s is the string, d is the intiger.



来源:https://stackoverflow.com/questions/11602536/strings-wont-be-translated-in-django-using-format-function-available-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!