from flask import Flask, render_template

app = Flask(__name__)


# 定义类用于参数传递
class User:
    """
    对于参数age是后续加上去的,因为前期已经对于类进行过实例化了,所以在增加参数时,最好给上一个默认值.
    不然之前的写法都要重新修改.
    """
    def __init__(self, name, e_mail, age=18):
        self.name = name
        self.e_mail = e_mail
        self.age = age


@app.route("/")
def hello_world():
    return render_template("base.html")


# 子模版01的路由
@app.route("/child01")
def child01():
    # 模板继承,
    return render_template("child01.html")


# 子模版02的路由
@app.route("/child02")
def child02():
    # 模板继承,
    return render_template("child02.html")


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5001, debug=True)

模板调用效果:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
<!--    这里通过挖坑(block)的方式自定义标题,给子模板使用-->
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
<!--同理这里是也是挖坑(block).-->
<!--加入导航条-->
<ul>
    <li><a href="#">首页</a></li>
    <li><a href="#">新闻</a></li>
</ul>
{% block body %}
{% endblock %}
<footer>这是底部的标签</footer>
</body>
</html>
base.html

子模版01调用效果:对于标题和内容已经动态添加进去。

<!--extends继承模板-->
{% extends "base.html" %}
<!--block是在基类模板中挖好的坑-->
{% block title %}
我是子模版01的标题
{% endblock %}
{% block body %}
我是子模版01的字幕
{% endblock %}
child01.html

子模版02调用效果:对于标题和内容已经动态添加进去。

 child02.html

 

posted on 2024-03-21 13:42  子线  阅读(33)  评论(0)    收藏  举报