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?
The solution was to install Flask Babelex instead of Babel.
... 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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With