在Bottle.py中将Mako设置为默认模板引擎
有没有办法在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
我尝试过:
- 把.html改成.mako
- 使用了
renderer
插件:app.route(..., renderer='mako'
) - 试过不同的格式:
# 甚至用了'.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))
3 个回答
0
在编程中,有时候我们会遇到一些问题,特别是在使用某些工具或库的时候。比如说,当你在写代码时,可能会发现某个功能没有按照预期工作。这时候,很多人会去网上查找解决方案,比如在StackOverflow上提问或者寻找答案。
在这些讨论中,大家会分享他们的经验和解决办法。有时候,问题的根源可能是因为代码中的小错误,或者是对某个功能的理解不够深入。通过查看别人的问题和答案,我们可以学到很多,避免自己在同样的地方犯错。
总之,编程是一条不断学习的路,遇到问题时不要气馁,去寻找答案,和其他人交流,最终你会变得越来越熟练。
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}
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()
1
你可以从你的路由函数中返回一个Mako模板:
from bottle import mako_template as template
def func():
...
return template('mytemplate.mako')
编辑:
bottle.mako_view
可能正是你需要的。我自己还没试过,但类似这样的代码可能会有效:
app.route(path='/', method='GET', callback=func, apply=[auth, mako_view('index.html')])