状况1:一般写页面都有个模板用来框定头部LOGO页面,左侧导航菜单,只有右部的内容不一样。若是不使用模板就大量重复工做。
特别若是头部或者左侧导航须要修改或者添加,全部页面都须要修改。django 经过模板继承解决。
状况2:一个页面若是内容特别多,不可能都一块儿写同一个页面。好比京东首页内容很是多。如何解决了?django经过include导入其余页面。
1)继承使用css
步骤1:母板里写入block,就能够被继承,content是名称 html
{% block title %} {% endblock%} {% block “content“ %} {% endblock%}
步骤2:子页面经过extends指定继承那个模板jquery
{% extends 'master.html'%} #继承那个模板 {% block “content“ %} 这个地方就是替换模板block “content“ <ul> {% for i in u%} <li>{{i}}</li> {%endfor%} {% endblock%}
2)若是子页面有本身的css,js 怎么用了?
A)若是是在子页面写CSS和JS,CSS就不是在头部了,而JS也不是在<body>以前,假如要引用jquery,子页面写的JS会在jquery引用前面,就会不生效django
B)继承CSS与JS都是共有的。
bootstrap
解决方法:url
在模板里css 和js位置在写个block块。而后在block里引入,在这个block写本身的js和css
注:block和顺序没有关系spa
3)一个页面只能继承一个模板,如何解决了?如何使用多个模板,或者引入其余页面code
<% include "a.html" %> 能够引用屡次htm
4)模板,include,子页面怎么渲染?
先把本身渲染成字符串,在拿模板和include渲染,因此不存在渲染问题(能够把子页面继承include当作一个整页面)blog
#url.py url(r'^tpl1$',views.tpl1), url(r'^tpl2$',views.tpl2), url(r'^tpl3$',views.tpl3), #views.py def tpl1(request): u=[1,2,3] return render(request,"tp1.html",{"u":u}) def tpl2(request): name="alex" return render(request,"tp2.html",{"name":name}) def tpl3(request): status="已修改" return render(request,"tp3.html",{"status":status}) #模块:master.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> {% block title %}{% endblock %} <!--这里用来设置标题--> </title> <link rel="stylesheet" href="/static/common.css"> {% block css %}<!--这里用来设置子页面本身的css--> {% endblock %} </head> <body> {% block content %}<!--这里用来设置子页面本身的内容--> {% endblock %} <script src="/static/js/jquery-1.12.4.js"></script> <script src="/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script> {% block js %}<!--这里用来设置子页面本身的js--> {% endblock %} </body> </html> #子页面:tp1.html {% extends "master.html" %} <!-- 继承那个模板--> {% block title %} 用户管理 {% endblock %} {% block css %} <style> body{ background-color: aqua; } </style> {% endblock %} {% block content %} <h1>用户管理</h1> <ul> {% for i in u %} <li>{{ i }}</li> {% endfor %} </ul> {% endblock %} #子页面:tp2.html {% extends "master.html" %} {% block content %} <h1>修改密码{{ name }}</h1> {% include "tp3.html" %} <!-- 引入其余页面--> {% endblock %} #include页面:tp3.html <div> <input type="text"> <input type="button" value="++"> </div>