Tornado templates模板渲染语法总结
工作需要研究了一下tornado的模板渲染语法,写了个测试,总结了一下相关语法,聊作笔记如下。
tornado本身非常灵活,支持几乎所有python支持的模板语言。除此之外,它本身也提供了一个轻量级的模板,放在tornado.template
中。
测试用例
代码清单1:tornado_template.py
import tornado.httpserver
import tornado.ioloop
import tornado.web
# define one "add" customization funcation which will be used in the assigned template file.
def add(x, y):
return (x+y)
class MainHandler(tornado.web.RequestHandler):
def get(self):
items = ["item1","item2","item3"]
# render the corresponding template file, and pass the "**args" to the assigned template
# not only we can pass the realted parameters, but also can pass the related functions.
# so extendible and powerful! :)
items2 = ["item1", "item2"]
def checked(item):
return 'checked=checked' if item in items2 else ''
self.render("template_test.html", items=items, add=add, items2=items2, checked=checked)
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8081)
tornado.ioloop.IOLoop.instance().start()
代码清单2:template_test.html
<html>
<head>
<title>template function test</title>