我正在使用 flask-babel 来翻译基于 Flask 的网络应用程序。我真的很想知道如何翻译变量的内容,比如 foo
。
我尝试了 {{ _(foo) }}
,但是当我像这样更新 .po
文件时:
pybabel extract -F babel.cfg -k lazy_gettext -o messages.pot .
pybabel update -i messages.pot -d translations
翻译foo
变量的内容时不显示任何内容。
常量字符串都可以,比如 {{ _("goo")}}
。
最佳答案
你不能提取一个变量,因为在表达式中 _(some_variable)
some_variable
是在运行时查找的。如果您从静态值列表中获取 some_variable
,则静态值将被提取。例如:
COLORS_OF_MAGIC = [_("green"), _("red"), _("blue"), _("white"), _("black")]
def color_for_index(index):
if not (0 < index > len(COLORS_OF_MAGIC)):
index = 0
return COLORS_OF_MAGIC[index]
def do_work():
index = get_index_from_user()
some_variable = color_for_index(index)
return _("You chose ") + _(some_variable) + _(" as the color of magic")
将具有以下值:green
、red
、blue
、white
、black
,You choose
,作为 PO 文件中的魔法颜色
。
另一方面,如果您正在尝试翻译用户提供的字符串,那么您将需要另一种解决方案,因为 Babel 是一种静态翻译服务。
关于python - flask-babel:如何翻译变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34579316/