Python, flask, babel- message, and e.g. Spanish - How to


I am utterly confused with trying to use babel with flask for language translation.

Lets assume the following. A user has a preferance of spanish over english. I have a variable that marks this:


Lets say I have to messages, one on english and the other in spanish that I want to display. 'Please' vs 'por fovor'


Here is my base babel config file

[python: **.py]
[jinja2: **/templates/**.html]

So, where does 'Please' go and how is it mapped to 'por fovor' if user pref is spanish?

Then, how to I call from a template based on language profile?


12/22/2012 5:11:44 PM

Accepted Answer

Flask-Babel is really great project. If you looking for jinja, i18n and Flask on google, you will find some useful examples. Please see docs for more info. Here I'll provide a little example:

1. Create the translations dir:


Assuming that your site is in Portuguese and English. It is a manual way to do that. You'd better use pybabel init command.

2. Create a file named messages.po (these files will contain translated strings):

$ touch my_website/translations/pt/LC_MESSAGES/messages.po 
$ printf "msgid \"Hello world\"\nmsgstr \"Olá mundo\"" > my_website/translations/pt/LC_MESSAGES/messages.po
$ cat my_website/translations/pt/LC_MESSAGES/messages.po

It will create a file with the follow content:

msgstr "Olá mundo"

3. Compile translation

 $ pybabel compile -d translations

4. Added line code this to your flask's main app file.

app.config['BABEL_DEFAULT_LOCALE'] = 'pt_BR' #(context locale to load language).

5. Use _() function in your jinja's template file in order to see Olá mundo string.

<h1>{{ _('HELLO WORLD') }}</h1>

I hope it'll be useful.

6/15/2016 2:40:42 PM

Have you runned the pybabel translation as explained in the guide?

And see and

It seems you can simply use _()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow