(更新)
这个答案提供了使用 Jinja 的通用说明,但是
看起来bottle 有自己特殊的做事方式。你
需要忽略关于环境和过滤器的 Jinja 文档,
而是钻研瓶源;具体来说,
Jinja2Template,看起来像这样:
class Jinja2Template(BaseTemplate):
def prepare(self, filters=None, tests=None, globals={}, **kwargs):
from jinja2 import Environment, FunctionLoader
self.env = Environment(loader=FunctionLoader(self.loader), **kwargs)
if filters: self.env.filters.update(filters)
...
请注意,prepare 方法接受 filters 关键字参数,用于在其创建的环境中设置过滤器。
jinja2_template 函数,其定义如下:
jinja2_template = functools.partial(template, template_adapter=Jinja2Template)
最后,template 函数,它包括:
if tplid not in TEMPLATES or DEBUG:
settings = kwargs.pop('template_settings', {})
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)
所以,当您致电 jinja2_template("foo.html")(这就是您
做),这变成:
template("foo.html", template_adapter=Jinja2Template)
在template 函数中,模板将调用prepare
Jinja2Template 的方法,带有来自 settings 的关键字参数,
它来自template_settings 到template 的参数。所以,
我们可以使用这样的自定义过滤器:
import bottle
def hellofilter(value):
return value.replace("hello", "goodbye")
@bottle.get("/foo")
def foo():
settings = {
"filters": {
"hello": hellofilter,
}
}
return bottle.jinja2_template("foo.html", template_settings=settings)
if __name__ == "__main__":
bottle.run(host="127.0.0.1", port=7070, debug=True)
如果我的模板foo.html 看起来像这样:
This is a test. {{ "hello world"|hello }}
请求127.0.0.1:7070/foo 将返回:
This is a test. goodbye world
如果我们不想每次都传递 template_settings 参数
我们打电话给jinja2_template,我们可以自己使用functools.partial
为jinja2_template 函数创建一个包装器:
import bottle
import functools
def hellofilter(value):
return value.replace("hello", "goodbye")
template_settings = {
"filters": {
"hello": hellofilter,
},
}
template = functools.partial(
bottle.jinja2_template, template_settings=template_settings
)
@bottle.get("/foo")
def foo():
return template("foo.html")
if __name__ == "__main__":
bottle.run(host="127.0.0.1", port=7070, debug=True)