使用模板的继承可以重复使用相同结构的模板, 可以大大减少代码量
入门实例
一、demo目录结构

注解:
master.html为模板内容,被index.html,account.html引用
二、各文件代码
2.1、master.html
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Master</title>
6 <style>
7 *{
8 margin: 0;
9 padding: 0;
10 }
11 .page-header{
12 height: 48px;
13 background-color: aqua;
14 }
15 .page-content{
16 height: 300px;
17 background-color: bisque;
18 }
19 .page-footer{
20 height: 30px;
21 background-color: aqua;
22 }
23 </style>
24
25 </head>
26 <body>
27 <div class="page-header"></div>
28 <div class="page-content">
29 <!-- 自定义的内容,命名并占位-->
30 {% block tm_content %}
31 {% end %}
32 </div>
33 <div class="page-footer"></div>
34 <!-- 自定义的js文件位置,命名并点位-->
35 {% block tm_js %}
36 {% end %}
37
38 <!-- 自定义css,命名并占位-->
39 {% block tm_css %}
40 {% end %}
41 </body>
42 </html>
2.2、form.html
<form>
<input type="text"/>
<input type="submit" value="提交"/>
</form>
2.3、account.html
1 {% extends "../template/master.html" %}
2
3 <!--自定义css具体内容-->
4 {% block tm_css %}
5 <script type="text/css">
6 .page-content{
7 background-color: aliceblue;
8 font-size: 20px;
9 }
10 </script>
11 {% end %}
12
13 <!--自定义page-content中的内容-->
14 {% block tm_content %}
15 <p>这是我的account</p>
16 {% end %}
17
18 <!--自定义js文件-->
19 {% block tm_js %}
20 <script type="text/javascript">
21 console.log("这是我的account")
22 </script>
23 {% end %}
2.4、index.html
{% extends "../template/master.html"%}
<!--对应的自定义css具体内容-->
{% block tm_css %}
<style type="text/css">
.page-content{
background-color: cornflowerblue;
}
</style>
{% end %}
<!--自定义page-content的内容-->
{% block tm_content %}
<p>这是系统的首页</p>
{%include "../include/form.html" %}
{%include "../include/form.html" %}
{% end %}
<!--自定义js的内容-->
{% block tm_js %}
<script type="text/javascript">
console.log("这是系统的首页")
</script>
{% end %}
2.5、start.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # @Time : 2019/12/5 23:41
4 # @Author : yusheng_liang
5 # @Site :
6 # @File : start.py
7 import tornado.web
8 import tornado.ioloop
9
10 class IndexHandle(tornado.web.RequestHandler):
11 def get(self, *args, **kwargs):
12 self.render("extend/index.html")
13
14 class AccountHandle(tornado.web.RequestHandler):
15 def get(self, *args, **kwargs):
16 self.render("extend/account.html")
17
18 if __name__ == "__main__":
19 CONTENTS_LIST = []
20 settings = {
21 'template_path': 'views',
22 }
23
24 application = tornado.web.Application([
25 (r"/index", IndexHandle),
26 (r"/account", AccountHandle),
27 ], **settings)
28
29 application.listen(80)
30 tornado.ioloop.IOLoop.instance().start()
三、demo效果示例
3.1、http://127.0.0.1/index

3.2、http://127.0.0.1/account

详解分析
- 从运行结果来看, 两个网页的主体结构相同, 只是里边包含的
css具体样式, 具体内容以及js文件不同 - 要继承模板文件来使用我们要在当前文件首行写上
{%extends "../template/master.html"%}, 这里表示当前文件以master.html来进行渲染 - 在
master.html文件中{%block tm_css%}{%end%}相当与为后面具体要写入的内容做一个占位符, 并且起名为tm_css