tornado 5、模板扩展

来源:互联网 发布:淘宝大学证书 编辑:程序博客网 时间:2024/04/29 18:57

一.介绍

为了减少重复写相同代码,tornado提供代码基础与block功能来减少我们工作量。假设我们在模板路径下有两个模板:index.html,base.html。

二.继承template

base.html内容如下:

   <!DOCTYPE html>    <html>    <head>        <title></title>    </head>    <body>        base内容    </body>    </html>

index.html内容如下:

{% extends "base.html" %}

当我们使用self.render(“index.html”)渲染时会发现index拥有base里的所有内容。

三.块block

base.html内容如下:

<!DOCTYPE html><html lang="zh-CN">  <head>    <meta charset="utf-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1">    <title>{{title}}-模式</title>  </head>  <body>    <div class="container">      <div class="row">        <div class="col-md-9">          {% block contain %}{% end %}        </div>      </div>    </div>  </body></html>

index.html内容如下:

{% extends base.html %}{% block contain %}111111111{% end %}

当我们使用self.render(“index.html”)渲染时会发现index拥有base里的所有内容。并且index中block contain中内容被插进了main container里。渲染如下

<!DOCTYPE html><html lang="zh-CN">  <head>    <meta charset="utf-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1">    <title>标题-模式</title>  </head>  <body>    <div class="container">      <div class="row">        <div class="col-md-9">                111111111         </div>      </div>    </div>  </body></html>

四.UI模块

1.继承tornado.web.UIModul

 class HelloModule(tornado.web.UIModule):      def render(self):         return '<h1>Hello, world!</h1>'

2.设置Application中

ui_modules={'Hello', HelloModule}

3.在模板中使用

{% module Hello() %} 

整个文件如下:

import tornado.webimport tornado.httpserverimport tornado.ioloopimport tornado.optionsimport os.pathfrom tornado.options import define, optionsdefine("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()    <head><title>UI Module Example</title></head>    <body>        {% module Hello() %}    </body></html>
0 0