Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask Babel Translations path

I have a webapp that uses Flask Babel to translate the templates. This webapp can use multiple databases by adding the database name to its url, like:

myapp.com/<dbname>

The problem is that translations path is hardcoded in babel:

    def list_translations(self):
        """Returns a list of all the locales translations exist for.  The
        list returned will be filled with actual locale objects and not just
        strings.

        .. versionadded:: 0.6
        """
        dirname = os.path.join(self.app.root_path, 'translations')
        if not os.path.isdir(dirname):
            return []
        result = []
        for folder in os.listdir(dirname):
            locale_dir = os.path.join(dirname, folder, 'LC_MESSAGES')
            if not os.path.isdir(locale_dir):
                continue
            if filter(lambda x: x.endswith('.mo'), os.listdir(locale_dir)):
                result.append(Locale.parse(folder))
        if not result:
            result.append(Locale.parse(self._default_locale))
        return result

And babel is forcing me to the directory named "translations" and to the language file named "messages.mo"

I tried all over the internet, but still no clear solution for this problem.

One idea I had in mind, is it possible to change babel with babelex and then I can override translations path?

like image 408
xyro Avatar asked Oct 21 '14 13:10

xyro


2 Answers

The solution was to install Flask Babelex instead of Babel.

like image 26
xyro Avatar answered Oct 10 '22 16:10

xyro


... Some years later, get a clue in github . Since version 0.6, Babel seems to have poorly documented parameter BABEL_TRANSLATION_DIRECTORIES. Then the Flask app skeleton should be

# example.py
from flask import Flask
app = Flask('example')

# change path of messages.mo file
app.config['BABEL_TRANSLATION_DIRECTORIES'] = 'i18n'

# add translation capacity
from flask.ext.babel import Babel
babel = Babel(app)

# define routes and so on ...

With this configuration, Flask will look for translation first in dir 'i18n'.

A very basic jinja template

{{_('hello')}}

The directory tree with 2 languages. Files messages.po should contain translation of 'hello'

/myProject
  /i18n
    /en
      /LC_MESSAGES
        messages.po
    /fr
      /LC_MESSAGES
        messages.po
  example.py

Bonus : for multiple directories use

app.config['BABEL_TRANSLATION_DIRECTORIES'] = 'i18n;second_dir;third_dir'
like image 82
simedia Avatar answered Oct 10 '22 16:10

simedia