14、模板的繼承
阿新 • • 發佈:2022-06-01
定義模板檔案 base.html
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>{% block title %}這是基模板中的網頁標題{% endblock %}</title>
</head>
<body>
{% block body %}這是基模板中的內容{% endblock %}
</body>
</html>
定義主頁模板 index.html
{# 繼承自 base.html 模板 #} {% extends "base.html" %} {# 修改基模板中的網頁標題 #} {% block title %}網站首頁{% endblock %} {% block body %} {{ super() }} {# 繼承內容 #} {# 新增內容 #} <h4>這是網站首頁的內容!</h4> {% endblock %}
定義產品頁模板 product.html
{# 繼承模板 #}
{% extends "base.html" %}
{% block title %}產品列表頁{% endblock %}
{% block body %}
<h4>這是產品列表頁的內容!</h4>
{# self.title() 表示取得本頁面的網頁標題 #}
<h4> 取得網頁標題的內容:{{ self.title() }}</h4>
{% endblock %}
定義主程式
from flask import Flask,render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/product') def product(): return render_template('product.html') if __name__ == '__main__': app.run(debug=True)