flask-模板全局函数

2022-07-27  本文已影响0人  测试探索

一、全局函数

image.png
image.png

二、目录与代码

image.png

app.py

from flask import Flask,render_template,render_template_string,g,url_for

app = Flask(__name__)
app.jinja_env.add_extension('jinja2.ext.loopcontrols')


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

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

@app.route('/gf')
def global_func():
    """模板全局函数的使用"""
    return render_template("global_func.html")


if __name__ == '__main__':
    app.run(debug=True)


global_func.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>全局函数的使用</title>
    <link rel='stylesheet' href = "{{ url_for('static',filename = 'style.css')}}">
    <style type = "text/css">
        .row1{
            color: #ff0000;
        }

        .row2{
            color: #0000ff;
        }
    </style>
</head>
<body>
    <h3>url_for的使用</h3>
    <a href = "{{ url_for('index')}}">回到首页</a>
    <a href = "{{ url_for('tag')}}">跳转到标签练习页</a>

    <h3>range函数的使用</h3>
    {% for i in range(5) %}
        <p>{{ i }}</p>
    {% endfor %}

    <h3>cycler函数的使用</h3>
    {% set class_name = cycler('row1','row2') %}
    {% for i in range(100) %}
        <p class = "{{ class_name.next()}}">{{ i }}</p>
    {% endfor %}
</body>
</html>
image.png
上一篇下一篇

猜你喜欢

热点阅读