一:繼承
基類模板base.html 中在進行挖坑 {% block 坑的名字%}{% endblock %}
子類模板test.html 中 通過 {% extends "base.html" %} 繼承父類模板,然后進行填坑,{% block 坑的名字 %}{% endblcok %}
填坑的方式有兩種:
1. 直接使用父類的坑,不進行更改,那就在子類中調用super()方法,顯示父類同樣位置坑的內容。
{% block 坑的名字 %}{{ super() }}{% endblcok %}
2. 使用父類的坑,並進行更改的,
{% block 坑的名字 %}這是更改的內容{% endblcok %}
實例:
base.html
<!doctype html> <html lang="zh-hans"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div style="background-color: red">{% block head %}{% endblock %}</div> <br> <div style="background-color: yellow">{% block body %}{% endblock %}</div> <br> <div style="background-color: green">{% block foot %}{% endblock %}</div> </body> </html>
test1.html
{% extends 'base.html' %}
{% block head %}
<h1>這是繼承父類模板的頭部內容</h1>
{% endblock %}
{% block body %}
<h2>這是繼承父類的中間內容</h2>
{% endblock %}
{% block foot %}
<h3>這是繼承父類模板的底部內容</h3>
{% endblock %}
視圖函數
from flask import Flask from flask import request from flask import redirect from flask.ext.script import Manager from flask import render_template app = Flask(__name__) app.config["secret_key"] = "hard to guess" @app.route("/") def index(): return "這是主頁" @app.route("/test") def templates(): return render_template("test1.html") if __name__ == "__main__": app.run(debug=True)
瀏覽器顯示

對父類模板的div布局和樣式進行了繼承,同時子類模板中,還進行了文字內容的添加,以及文字大小的設置。
