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

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


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:

my_website/translations/pt/LC_MESSAGES/my_website/translations/en/LC_MESSAGES/

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:

msgid "HELLO WORLD"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.