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


Question

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:

g.user.default_language='sp'

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

<html>
<h1>INSERT TRANSLATION HERE</h1>
</html>

Here is my base babel config file

[python: **.py]
[jinja2: **/templates/**.html]
extensions=jinja2.ext.autoescape,jinja2.ext.with_

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?

Thanks

1
4
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:

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.

6
6/15/2016 2:40:42 PM

Have you runned the pybabel translation as explained in the guide? http://packages.python.org/Flask-Babel/

And see http://jinja.pocoo.org/docs/templates/#i18n-in-templates and http://jinja.pocoo.org/docs/integration/#babel-integration

It seems you can simply use _()


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