django基础(十)之模板继承
模板继承
背景:在大多数情况下,很多页面都有相同css和菜单页,如果有相同样式的一个页面更改时,其它页面的样式也得随着更改,麻烦的同时也会加大工作量,这就出现了模版继承
一、extends
方法
{% block name %}{% endblock %} 其中name为自定义名称,引用时要写对
示例:
先看一下示例图:主页
用户编辑页面
代码实例: (master.html,userinfo.html,edit.html)
master.html为被继承的模版文件,存放userinfo.html和edit.html页面相同的样式
master.html
##蓝色覆盖部分为模版被继承后,子页面要修改成自己所需的部分(黑色字体代码表示两个页面的相同部分)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> #这里的title为自定义的名称,引用时要写上 <style> .menu{ display: block; padding:5px; } </style> </head> <body style="margin: 0;"> <div style="height:48px;background-color: black;color: red;"> </div> <div> <!--左边菜单--> <div style="position: absolute;top:48px;left: 0;bottom: 0;width: 200px;background-color: red"> <a class="menu" href="/cmdb/userinfo">用户管理</a> <a class="menu" href="/cmdb/usergroup_info">用户组管理</a> </div> </div> {% block common %} {% endblock %} <script src="/static/jquery-3.2.1.js"></script> {% block js %}{% endblock %} ##表示将js部分放到这里 </body> </html>
userinfo.html和edit.html
#userinfo.html {% extends 'master.html' %} ###继承master.html模版 {% block title %}用户详细信息{% endblock %} ##将继承的模版的title 改成自己定义的名称 {% block common %} ##将继承的模版的common内容 改成自己定义的common内容(相当于将自己定义的东西填进去) ###block common 这里的common 要与master里定义的名字相同,表示将common这部分下的内功代替模版里的这部分 <div style="position: absolute;top:48px;left:210px;right: 0;bottom: 0;overflow: auto;"> <h1>用户列表</h1> <ul> {% for row in userlist %} <li> <a href="/cmdb/userdetail-{{ row.id }}">{{ row.username }}</a>| <a href="/cmdb/useredit-{{ row.id }}">{{ row.user_group.caption }}</a>| <a href="/cmdb/userdel-{{ row.id }}">删除</a>| <a href="/cmdb/useredit-{{ row.id }}">编辑</a> </li> {% endfor %} </ul> <h2>添加用户</h2> <form action="/cmdb/userinfo/" method="POST"> <input type="text" name="username"/> <input type="password" name="password"/> <select name="group_id"> {% for item in grouplist %} <option value={{ item.uid }}>{{ item.caption }}</option> {% endfor %} </select> <input type="submit" value="添加"/> </form> </div> {% endblock %} #edit.html {% extends 'master.html' %} ###继承master.html模版 {% block title %}编辑用户{% endblock %} {% block common %} <div style="position: absolute;top:48px;left:210px;right: 0;bottom: 0;overflow: auto;"> <h1>用户编辑</h1> {% for row in user_infomation %} <form action="/cmdb/useredit-{{ row.id }}/" method="POST"> <input style="display: none" type="text" name="id" value={{ row.id }} /> <input type="text" name="username" value={{ row.username }} /> <input type="text" name="password" value={{ row.password }} /> <input type="submit" value="提交"> </form> {% endfor %} </div> {% endblock %} {% block js %} ###表示继承js部分 <script> alert('/xss/') </script> {% endblock %}
二、include
userinfo.html
tag.html
自定义函数继承
继承某个py文件,引用里面的函数