Django模版引擎中最强大也是最复杂的部分就是模版继承了。模版继承可以让您创建一个基本的“骨架”模版,它包含您站点中的全部元素,并且可以定义能够被子模版覆盖的 block。
模板继承:
1. 新建muban.html模板文件,在形影需要替换的不同位置加上不同名称的block标签
{% block content %}
模板内容
{% endblock %}或者{% endblock content %}
2. 在新的html文件开头写:
{% extends "muban.html" %}
3. 接下来重写模板中的block标签内容:
注意:每个block标签不能同名,可以有多个(一般css/js/内容都可以有)
{% block content %}
……
{% endblock %}或者{% endblock content %}
4. 要想继承保留模板block中的内容,在重写时加上
{{ block.super }}
模板继承演示:
muban.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <style> 6 * {margin: 0; padding: 0; } 7 .c1, .nav {margin: 0 auto; width: 1200px; background-color: #d6d6d6; color: white; } 8 .fixed:after {content: "";display: block; clear: both; } 9 .navleft {float: left; } 10 .navright {float: right; } 11 ul, li {list-style: none; display: inline; } 12 .contentleft {float: left; width: 300px; background-color: red; height: 100px; } 13 .contentright {float: left; width: 900px; height: 100px; background-color: green; } 14 .c2 {margin: auto auto; text-align: center;vertical-align: middle; } 15 </style> 16 <title>模板继承测试</title> 17 </head> 18 <body> 19 <div class="c1"> 20 <div class="nav fixed"> 21 <div class="navleft "> 22 <ul> 23 <li>古诗</li> 24 <li>绝句</li> 25 <li>诗经</li> 26 </ul> 27 </div> 28 <div class="navright"> 29 <ul> 30 <li>登录</li> 31 <li>注册</li> 32 </ul> 33 </div> 34 </div> 35 36 <div class="content fixed"> 37 <div class="contentleft"> 38 <div class="c2"> 39 <a href="http://127.0.0.1:8888/muban/">简介</a><br> 40 <a href="http://127.0.0.1:8888/muban_1/">古诗1</a><br> 41 <a href="http://127.0.0.1:8888/muban_2/">古诗2</a></div> 42 </div> 43 <div class="contentright"> 44 <div class="c2"> 45 {% block content %} 46 模板内容---简介 47 {% endblock %} 48 </div> 49 </div> 50 </div> 51 52 </div> 53 </body> 54 </html>
muban_1.thml
1 {% extends "muban.html" %} 2 {% block content %} 3 <h2>You never fail just when you give up!</h2> 4 {% endblock %}
muban_2.thml
1 {% extends "muban.html" %} 2 {% block content %} 3 {{ block.super }}<!--继承保留模板对应标签的内容--> 4 <h2>Do whatever you want and smile veryday!</h2> 5 {% endblock %}
views.py
1 def muban(request): 2 return render(request,"muban.html") 3 def muban_1(request): 4 return render(request,"muban_1.html") 5 def muban_2(request): 6 return render(request,"muban_2.html")
渲染效果