Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

like image 918
Tampa Avatar asked Jan 15 '23 20:01

Tampa


2 Answers

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.

like image 50
Jonathan Simon Prates Avatar answered Jan 21 '23 16:01

Jonathan Simon Prates


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 _()

like image 35
Martin Samson Avatar answered Jan 21 '23 17:01

Martin Samson