一、继承的实现

image.png

image.png

image.png
二、目录结构和代码

image.png
app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
""" 首页 """
return render_template('index.html')
@app.route('/course')
def course():
""" 免费课程 """
return render_template('course.html')
@app.route('/coding')
def coding():
""" 实战课程 """
return render_template('coding.html')
@app.route('/article')
def article():
""" 手记 """
return render_template('article.html')
@app.route('/wenda')
def wenda():
""" 实战课程 """
return render_template('wenda.html')
if __name__ == '__main__':
app.run(debug=True)
公共部分--base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页-慕课网</title>
<style type="text/css">
.container {
width: 600px;
height: 500px;
margin: 0 auto;
}
header {
background: aqua;
}
article {
background: azure;
height: 500px;
}
footer {
background-color: coral;
}
</style>
</head>
<body>
<div class="container">
<header>
页面头部[首页 免费课程 实战课程 金职位 专栏 猿问 手记]
</header>
<article>
{% block content %}
首页课程内容
{% endblock %}
</article>
<footer>页面底部</footer>
</div>
</body>
</html>
继承页面:首页-index.html
{% extends 'base.html' %}
{% block content %}
首页课程内容
{% endblock %}

image.png
继承页面:免费课程:course.html
{% extends 'base.html' %}
{% block content %}
免费课程内容
{% endblock %}

image.png
三、复用父模板的内容(可选)

image.png
base.html该部分对header进行了更改
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页-慕课网</title>
<style type="text/css">
.container {
width: 600px;
height: 500px;
margin: 0 auto;
}
header {
background: aqua;
}
article {
background: azure;
height: 500px;
}
footer {
background-color: coral;
}
</style>
</head>
<body>
<div class="container">
<header>
{% block header %}
页面头部[首页 免费课程 实战课程 金职位 专栏 猿问 手记]
{% endblock %}
</header>
<article>
{% block content %}
<p>
课程内容
</p>
{% endblock %}
</article>
<footer>页面底部</footer>
</div>
</body>
</html>
index.html:首页的header,进行了变更,并且content部分进行了super().注意查看效果
{% extends 'base.html' %}
{% block header%}
首页的顶部导航
{% endblock %}
{% block content %}
{{ super() }}
<p>
首页课程内容
</p>
{% endblock %}

image.png
网友评论