如何使用jinja2 i18n与瓶(带巴贝尔)

时间:2014-04-25 01:02:51

标签: python internationalization jinja2 bottle babel

我相信使用jinja2和瓶子只需使用jinja2_template而不是模板: 例如bottle.jinja2_template(“mytemplate”,dict(name = value,name2 = value2)) 但是,如果需要i18​​n jinja扩展,那么如何最好地指定

....install_gettext_translations(

?这是用

自动完成的
bottle.jinja2_template("mytemplate", dict(name=value, name2=value2), template_lookup=['templates'],'template_settings'=   {'extensions':['jinja2.ext.i18n'],'autoescape': True }))

?感谢。

经过进一步的反思,我想我可能需要在Jinja2Template类中覆盖prepare方法来添加env.install_gettext_translations(???

更多信息,如果我正在做.... install_gettext_translations(手动,也许:

tenv = Environment(extensions=['jinja2.ext.i18n'])
tenv.install_gettext_translations(gettransobj())

import gettext
import locale 

def gettransobj():
    loc = locale.getlocale()
     # change to reflect where your mo files are
    mofilename = "res/messages_%s.mo" % locale.getdefaultlocale()[0][0:2]
    try:
       trans = gettext.GNUTranslations(open( mofilename, "rb" ) )
    except IOError:
       trans = gettext.NullTranslations()
    return trans

OR为babel翻译obj之类的东西

..... install_gettext_translations(gettransobj(),newstyle =真)

import babel
import locale 

def gettransobj():
  loc = locale.getlocale()
  mofilename = "res/messages_%s.mo" % locale.getdefaultlocale()[0][0:2]
  trans = babel.support.Translations(open( mofilename, "rb" ) )

如果这段代码有点正确,不知道放在哪里?对jinja2不太熟悉。只需一次在程序顶部或每瓶.jinja2_template调用。

另一方面,如果有人需要使用babel进行提取,请参阅jinja2.ext.babel_extract

另一种方法是通过以下方式获得trans obj:

return gettext.translation(domain, localedir=localedir,languages=languages, codeset='utf-8')

1 个答案:

答案 0 :(得分:2)

from jinja2 import FileSystemBytecodeCache, Environment
bcc = FileSystemBytecodeCache('/tmp', '%s.cache')

template_settings = {'filters': {
                       'tojson': json_util.dumps
                     },
                    'bytecode_cache': bcc,
                    'extensions': ['jinja2.ext.i18n'],
                    'languages': ['en_US']
                    }

import bottle
from bottle import Jinja2Template
from babel.support import Translations

TEMPLATE_PATH = bottle.TEMPLATE_PATH
DEBUG = bottle.DEBUG
TEMPLATES = {}

class Jinja2BabelTemplate(Jinja2Template):
    def prepare(self, filters=None, tests=None, 
                      languages=['en_US'], 
                      globals={}, **kwargs):
        from jinja2 import Environment, FunctionLoader
        self.env = Environment(loader=FunctionLoader(self.loader), **kwargs)
        #BABEL: this is where we load and install our translations from babel
        translations = Translations.load('translations', languages)
        self.env.install_gettext_translations(translations)
        if filters: self.env.filters.update(filters)
        if tests: self.env.tests.update(tests)
        if globals: self.env.globals.update(globals)
        if self.source:
            self.tpl = self.env.from_string(self.source)
        else:
            self.tpl = self.env.get_template(self.filename)


def jinja_template(*args, **kwargs):
    tpl = args[0] if args else None
    adapter = Jinja2BabelTemplate
    lookup = kwargs.pop('template_lookup', TEMPLATE_PATH)
    languages = kwargs.pop('languages', None)
    tplid = (id(languages), tpl,)
    if tplid not in TEMPLATES or DEBUG:
        settings = kwargs.pop('template_settings', {})
        if languages: settings.update({'languages': languages})    
        if isinstance(tpl, adapter):
            TEMPLATES[tplid] = tpl
            if settings: TEMPLATES[tplid].prepare(**settings)
        elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl:
            TEMPLATES[tplid] = adapter(source=tpl, lookup=lookup, **settings)
        else:
            TEMPLATES[tplid] = adapter(name=tpl, lookup=lookup, **settings)
    if not TEMPLATES[tplid]:
        abort(500, 'Template (%s) not found' % tpl)
    for dictarg in args[1:]: kwargs.update(dictarg)
    return TEMPLATES[tplid].render(kwargs)

template = functools.partial(jinja_template, 
                            template_settings=template_settings)


#and now you should be able to use the template function above with different languages

@get('/home')
def home():
     data = {}
     return template('home.html', data, languages=['en_US'])