认识tornado(五)

Tornado模板系统入门

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

首先是编写 URL 规则与 Handler:

01    class NowaMagicHandler(tornado.web.RequestHandler):
02        def get(self):
03            content = u'Welcome 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

转载于:https://www.cnblogs.com/work115/p/5588837.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值