Flask-template control statement

All control statements are placed in {%…%}, and there is a statement {% endxxx%} to end. The commonly used control statements in Jinja are if / for ... in ...
if: if statement is similar to that in python , You can use>, <, <=,> =, ==,! = To judge, you can also use and, or, not, () to perform logical merge operations

for ... in ...: For loop can traverse any sequence including list, dictionary, tuple. And it can be reversed traversal.
Insert picture description here
In addition, you can not use continue and break expressions to control the execution of the loop.

# @ Time : 2020/4/11 23:41
# @ Author : Ellen
from flask import Flask,render_template

app = Flask(__name__)
app.config["TEMPLATES_AUTO_RELOAD"] = True

@app.route("/")
def index():
    context = {
        "username": "ellen",
        "books": ["Python","Java","PHP"],
        "users":{
            "name": "ellen",
            "age": 19,
            "address": "shanghai"
        }
    }
    return render_template("if_for.html",**context)


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

Create if_for.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!-- {{ 变量 }} -->
{# {% 函数 if for %} #}


{% if username == "ellen1" %}
    <p>{{ username }}</p>
{% else %}
    <p>当前的用户名不是ellen...</p>
{% endif %}

{% for book in books %}
    <p>{{loop.index}}</p>
    <p>{{ book }}</p>
{% endfor %}

{% for user in users %}
    <p>{{ user }}</p>
{% endfor %}

{% for key,value in users.items() %}
    <p>{{ key }}</p>
    <p>{{ value }}</p>
{% endfor %}
<hr>
{% for key in users.keys() %}
    <p>{{ key }}</p>
{% endfor %}
<hr>
{% for value in users.values() %}
    <p>{{ loop.first }}</p>
    <p>{{ value }}</p>
{% endfor %}


</body>
</html>

Insert picture description here
Insert picture description here

Published 118 original articles · won praise 0 · Views 2663

Guess you like

Origin blog.csdn.net/weixin_45905671/article/details/105462306
Recommended