flask-babel: how to translate variables
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.
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.