码迷,mamicode.com
首页 > 其他好文 > 详细

认识tornado(五)

时间:2016-06-15 22:19:04      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:

Tornado 自带了模板系统,模板语法与 Django 差异不大。这里简单地介绍如何使用 Tornado 的模板系统。

首先是编写 URL 规则与 Handler:

01    class NowaMagicHandler(tornado.web.RequestHandler):
02        def get(self):
03            content = uWelcome to NowaMagic.
04            #self.write( content )
05            self.render("index.html")
06     
07    def main():
08        tornado.options.parse_command_line()
09        application = tornado.web.Application([
10            (r"/", MainHandler),
11            (r"/nowamagic/", NowaMagicHandler),
12        ],**settings)
13        http_server = tornado.httpserver.HTTPServer(application)
14        http_server.listen(options.port)
15        tornado.ioloop.IOLoop.instance().start()

然后是 index.html

01    <html>
02    <head>
03    <title>{{ title }}</title>
04    </head>
05    <body>
06      <h1>{{ title }}</h1>
07      <ul>
08        {% for item in items %}
09          <li>{{ escape(item) }}</li>
10        {% end %}
11      </ul>
12    </body>
13    </html>

文件包含也是用 {% include ‘header.html‘ %} 这样的语法,和 Django 里是一样的。

还有就是对静态文件的处理,一般是建一个叫 static 的文件夹,然后把js,css,images分类放进去。当然在程序里也得写个 setting:

1    import os
2     
3    settings = { 
4        "static_path" : os.path.join(os.path.dirname(__file__), "static"), 
5        "template_path" : os.path.join(os.path.dirname(__file__), "templates"), 
6        "gzip" : True, 
7        "debug" : True, 
8    }

setting 里还制定了模板的路径。关于这个 setting,更多可以参考这篇文章里提到的:如何开启Tornado的调试模式

就这样,Tornado 的模板就OK了。

 

认识tornado(一)
认识tornado(二)
认识tornado(三)
认识tornado(四)
认识tornado(五)

来源:http://www.nowamagic.net/academy/detail/1332566

认识tornado(五)

标签:

原文地址:http://www.cnblogs.com/work115/p/5588837.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!