3

我正在使用 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

没有任何内容用于翻译foovar 的内容。

常量字符串一切正常,例如{{ _("goo")}}.

4

2 回答 2

2

您无法提取变量,因为在_(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")

在 PO 文件中将具有以下值:greenredbluewhiteblackYou chose和。as the color of magic

另一方面,如果您尝试翻译用户提供的字符串,那么您将需要另一个解决方案,因为 Babel 是一个静态翻译服务。

于 2016-01-03T18:59:45.393 回答
0

遇到同样的问题。我需要翻译在运行时传递给 jinja2 的月份名称。我想出的解决方案是传递翻译后的名称。然后我所要做的就是声明一个在接受的答案中提到的静态名称列表。希望这可以帮助。

于 2017-10-11T06:47:13.840 回答