somenxavier
somenxavier

Reputation: 1557

flask-babel: how to translate variables

I am using flask-babel for translating a Flask-based web application. I really want to know how can I translate the content of a variable, say foo.

I try {{ _(foo) }}, but when I update the .po files like this:

pybabel extract -F babel.cfg -k lazy_gettext -o messages.pot .
pybabel update -i messages.pot -d translations

nothing is displayed for translating with the content of the foo var.

All is OK with constants strings, like {{ _("goo")}}.

Upvotes: 6

Views: 4438

Answers (2)

mljli
mljli

Reputation: 603

Ran into the same problem. I needed to translate month names that passed to jinja2 at runtime. The solution I came up with is to pass translated names. Then all I had to do is declare a static list of names as mentioned in the accepted answer. Hope this helps.

Upvotes: 0

Sean Vieira
Sean Vieira

Reputation: 159915

You cannot extract a variable, because in the expression _(some_variable) some_variable is looked up at run-time. If you are taking some_variable from a list of static values then the static values will be extracted. For example:

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

will have the values: green, red, blue, white, black, You chose, and as the color of magic in the PO file.

If, on the other hand, you are trying to translate user-provided strings then you will need another solution, as Babel is a static translation service.

Upvotes: 5

Related Questions