繁体   English   中英

在Bottle.py中将Mako设置为默认模板渲染器

[英]Set Mako as the default template renderer in Bottle.py

在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'
  • 尝试过不同的模式: # 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))

您可以从route函数返回一个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')])

看起来,目前尚无将默认模板更改为其他模板的方法,因此最终得到了一个临时解决方案(直到瓶中内置了某些东西-或直到找到它为止)。

这是临时解决方案:

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()
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}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM