tornado 5、模闆擴充
一.介紹
為了減少重複寫相同代碼,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 >
<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 >
<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.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()
<head><title>UI Module Example</title></head>
<body>
{% module Hello() %}
</body>
</html>
文章标簽: tornado