首页 > 代码库 > tornado 如何传递函数到模板

tornado 如何传递函数到模板

官方文档是这么写的

Translating directly to Python means you can apply functions to expressions easily, like the escape() function in
the examples above. You can pass functions in to your template just like any other variable (In a RequestHandler,
override RequestHandler.get_template_namespace):
### Python code
def add(x, y):

return x + y
template.execute(add=add)
### The template
{{ add(1, 2) }}



可是,没有完整的例子!!

于是按自己的想法写了一下:

class MonitorEditHandler(tornado.web.RequestHandler):
    #删除监控主机记录
    def get(self, *args, **kwargs):
        def add(a, b)
            return a+b

        with open('./static/hosts', 'rb+') as hosts:
            hosts = hosts.read()
        self.render(
            "monitor/monitor_edit.html",
            hosts=hosts,
            add = add
        )

在模板中直接使用{{add(1,2)}}就可以了!!