som*_*ier 5 python flask flask-babel python-babel
我正在使用 Flask-babel 来翻译基于 Flask 的 Web 应用程序。我真的很想知道如何翻译变量的内容,例如foo.
我尝试{{ _(foo) }},但是当我.po像这样更新文件时:
pybabel extract -F babel.cfg -k lazy_gettext -o messages.pot .
pybabel update -i messages.pot -d translations
Run Code Online (Sandbox Code Playgroud)
没有显示任何内容来翻译foovar 的内容。
常量字符串一切正常,例如{{ _("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")
Run Code Online (Sandbox Code Playgroud)
PO 文件中将包含以下值:green、red、blue、white、black、You chose、 和。as the color of magic
另一方面,如果您尝试翻译用户提供的字符串,那么您将需要另一个解决方案,因为 Babel 是静态翻译服务。