Flask Babel翻译路径

时间:2014-10-21 13:45:28

标签: python internationalization flask babel

我有一个使用Flask Babel翻译模板的webapp。 此Web应用程序可以通过将数据库名称添加到其URL来使用多个数据库,如:

myapp.com/<dbname>

问题是翻译路径在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

巴贝尔强迫我进入名为&#34的目录;翻译&#34;以及名为&#34; messages.mo&#34;

的语言文件

我在互联网上尝试过,但仍然没有明确解决这个问题的方法。

我想到的一个想法是,有可能用babelex改变babel然后我可以覆盖翻译路径吗?

3 个答案:

答案 0 :(得分:7)

......几年后,得到一条线索in github。从版本0.6开始,Babel似乎记录了参数 BABEL_TRANSLATION_DIRECTORIES 。那么Flask app骨架应该是

# 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 ...

使用此配置,Flask将首先在dir'i18n'中查找翻译。

一个非常基本的jinja模板

{{_('hello')}}

目录树有2种语言。 Files messages.po应该包含'hello'的翻译

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

奖励:对于多个目录使用

app.config['BABEL_TRANSLATION_DIRECTORIES'] = 'i18n;second_dir;third_dir'

答案 1 :(得分:2)

解决方案是安装Flask Babelex而不是Babel。

答案 2 :(得分:0)

为什么不直接将烧瓶零件加载到项目中并进行修改?