一个系统网站往往需要统一的结构,这样看起来比较“整洁”。
比如,一个页面中都有标题、左侧菜单、右侧内容显示、底部等四部分。
如果在每一个网页中都进行这些部分的编写,那么整个网站将会有很多冗余部分,而且,对于网页程序的编写也不美观。
这时候可以采用模板继承,即将相同的部分提取出来,形成一个base.html,具有这些相同部分的网页通过继承base.html来具有对应的模块。
这里采用的Jinja2中的模板继承机制来实现——将页面划分为标题栏、左侧菜单栏和右侧主页面。
base.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
{% block head %}
<link rel="stylesheet" href="{{url_for('static',filename='css/style.css')}}" />
<title>{% block title %}{% endblock %} - My Webpage</title>
{% endblock %}
</head>
<body>
<div id="content" style="background: #fff;width: 960px;margin:0 auto;">
<div style="width: 100%;height: 100px;background: #f00;position: relative;">
{% block content%}
{% endblock %}
</div>
<div style="width: 100%;height: 500px;background: #00f;position: relative;">
<div style="background: #ccc;width: 20%;float: left;height: 500px;">
{% block left %}
{% endblock %}
</div>
<div style="background: #fff;width: 80%;float: left;height: 500px;">
{% block right %}
{% endblock %}
</div>
</div>
</div>
<div id="footer">
<center>
{% block footer %}
© Copyright 2016 by <a href="http://www.baidu.com/">you</a>.
{% endblock %}
</center>
</div>
</body>
继承base的html
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ super() }}
<style type="text/css">
.important { color: #336699; }
</style>
{% endblock %}
{% block content %}
<h1>Index</h1>
<p class="important">
top-position
</p>
{% endblock content%}
{% block left %}
menu-position
{% endblock left%}
{% block right %}
main-position
{% endblock right%}
实现页面图:
其中:
<div id="content" style="background: #fff;width: 960px;margin:0 auto;">
<div style="width: 100%;height: 100px;background: #f00;position: relative;">
{% block content%}
{% endblock %}
</div>
<div style="width: 100%;height: 500px;background: #00f;position: relative;">
</div>
</div>
将页面划分为上下两部分;
<div style="width: 100%;height: 500px;background: #00f;position: relative;">
<div style="background: #ccc;width: 20%;float: left;height: 500px;">
{% block left %}
{% endblock %}
</div>
<div style="background: #fff;width: 80%;float: left;height: 500px;">
{% block right %}
{% endblock %}
</div>
</div>
将页面划分为左右两部分。