tornada模板学习笔记

时间:2021-03-29 20:37:30
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.options
import os.path from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int) class HelloHandler(tornado.web.RequestHandler):
def get(self):
self.render('hello.html') class HelloModule(tornado.web.UIModule):
def render(self):
return '<h1>Hello, world!</h1>' if __name__ == '__main__':
tornado.options.parse_command_line()
app = tornado.web.Application(
handlers=[(r'/', HelloHandler)],
template_path=os.path.join(os.path.dirname(__file__), 'templates'),
ui_modules={'Hello': HelloModule}
)
server = tornado.httpserver.HTTPServer(app)
server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()

ui_moudles参数期望一个模块名为键、类为值的字典输入来渲染它们

这个例子中ui_module字典里只有一项,它把到名为Hello的模块的引用和我们定义的HelloModule类结合了起来。

现在,当调用HelloHandler并渲染hello.html时,我们可以使用{% module Hello() %}模板标签来包含HelloModule类中render方法返回的字符串。

(Hello()相当于调用了HelloModule,因为前面的ui_modules={'Hello': HelloModule} 已经将两者结合,可以看成是一种别名)

<html>
<head><title>UI Module Example</title></head>
<body>
{% module Hello() %}
</body>
</html>