在Bottle中是否有一种方法可以将Mako设置为默认模板渲染器。
app.route(path='/', method='GET', callback=func, apply=[auth], template='index.html')
func : a function that returns a value (a dict)
auth : is a decorator for authentication
index.html : displays the values from the "func" and contains "Mako" syntax
renderer
插件:app.route(..., renderer='mako'
)# even used '.mako', 'index.mako', 'index.html.mako'
bottle
内部对象,但没有看到任何设置/更改默认引擎的提示:# Print objects that contains "template" keyword, the object itself, and its value
for i in dir(app):
if 'template' in i.lower():
print '{}: {}'.format(i, getattr(app, i))
答案 0 :(得分:1)
您可以从路线功能中返回Mako模板:
from bottle import mako_template as template
def func():
...
return template('mytemplate.mako')
编辑:
bottle.mako_view
可能是您正在寻找的内容。 Haven还没试过它,但是这样的事情可能就是这样的:
app.route(path='/', method='GET', callback=func, apply=[auth, mako_view('index.html')])
答案 1 :(得分:0)
看起来,目前没有办法将默认模板更改为其他内容,因此它最终得到了一个临时解决方案(直到瓶子内置了一些内容 - 或直到找到它为止)
这是临时解决方案:
import bottle as app
# Suppose this is the function to be used by the route:
def index(name):
data = 'Hello {}!'.format(name)
return locals()
# This was the solution (decorator).
# Alter the existing function which returns the same value but using mako template:
def alter_function(func, file_):
def wrapper(*args, **kwargs):
data = func(*args, **kwargs)
return app.mako_template(file_, **data)
return wrapper
# This really is the reason why there became a complexity:
urls = [
# Format: (path, callback, template, apply, method)
# Note: apply and method are both optional
('/<name>', index, 'index')
]
# These are the only key names we need in the route:
keys = ['path', 'callback', 'template', 'apply', 'method']
# This is on a separate function, but taken out anyway for a more quick code flow:
for url in urls:
pairs = zip(keys, url)
set_ = {}
for key, value in pairs:
set_.update({key:value})
callback = set_.get('callback')
template = set_.get('template')
set_['callback'] = alter_function(callback, template)
app.route(**set_)
app.run()
答案 2 :(得分:0)
import bottle
from bottle import(
route,
mako_view as view, #THIS IS SO THAT @view uses mako
request,
hook,
static_file,
redirect
)
from bottle import mako_template as template #use mako template
@route("/example1")
def html_example1(name="WOW"):
return template("<h1>Hello ${name}</h1>", name=name)
@route("/example2")
@view("example2.tpl")
def html_exampl2(name="WOW"):
#example2.tpl contains html and mako template code like: <h1>${name}</h1>
return {"name" : name}