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