存在问题:
django开发中,不同页面样式相同,如何共用一套母版,避免每个页面都重复写样式;
解决方案:
- 添加一个母版,如“layout.html”,在需要继承的位置添加{% block content %}{% endblock %} ;
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>页面通用模板(其他页面可继承)</title><link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"><link rel="stylesheet" href="{% static 'fonts/glyphicons-halflings-regular.woff' %}"><style>.navbar{border-radius: 0;}</style></head>
<body><!-- 导航栏-->
<nav class="navbar navbar-default"><div class="container"><div class="navbar-header"><button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button><a class="navbar-brand" href="#">用户管理系统</a></div><div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"><ul class="nav navbar-nav"><!--点击菜单栏部门管理,跳转到部门列表--><li><a href="/depart/list/">部门管理</a></li><li><a href="#">用户管理</a></li></ul><ul class="nav navbar-nav navbar-right"><li><a href="#">登录</a></li><li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">无佩奇 <span class="caret"></span></a><ul class="dropdown-menu"><li><a href="#">个人资料</a></li><li><a href="#">我的信息</a></li><li role="separator" class="divider"></li><li><a href="#">注销</a></li></ul></li></ul></div></div>
</nav><div>{% block content %}{% endblock %} #该页面为母版页面,其余页面继承该页面,集成时只需要替换此句位置的内容
</div><script src="{% static 'js/jquery-3.1.1.min.js' %}"></script><script src="{% static 'js/bootstrap.min.js' %}"></script>
</body>
</html>
- 页面继承,在新页面需要继承母版的地方添加{% extends ‘depart_layout.html’ %}
和{% block content %}{% endblock %}
{% extends 'depart_layout.html' %} #此处引用母版页面{% block content %} #此处为引入母版内容标识<div class="container"><div style="margin-bottom: 10px"><!--点击按钮新建部门,跳转到部门新增页面--><a class="btn btn-success" href="/depart/add/"><span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>新建部门</a></div><div class="panel panel-default"><div class="panel-heading"><span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>部门列表</div><table class="table table-bordered"><thead><tr><th>ID</th><th>部门名称</th><th>操作</th></tr></thead><tbody>{% for obj in querySet %}<tr><th>{{ obj.id }}</th><td>{{ obj.title }}</td><td><a class="btn btn-primary btn-xs" href="/depart/edit/?nid={{ obj.id }}">编辑</a><a class="btn btn-danger btn-xs" href="/depart/delete/?nid={{ obj.id }}">删除</a></td></tr>{% endfor %}</tbody></table></div></div>{% endblock %} #此处为引入母版内容标识