五、Jinja2—控制语句

73 阅读1分钟
一、if判断语句
from flask import Flask,render_template
app = Flask(__name__)

@app.route("/control")
def control():
    age = 10
    return render_template("control.html",age=age)

if __name__ == '__main__':
    app.run(debug=True,host="0.0.0.0",port=8000)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>if判断语句</title>
</head>
<body>
{% if age>18 %}
<div>您{{age}}岁了,可以单独进入网吧啦!</div>
{% elif age==18 %}
<div>您刚刚{{age}}岁,需要成年人陪同进入网吧!</div>
{% else %}
<div>您才{{age}}岁,不能进入网吧!</div>
{% endif %}
</body>
</html>
二、for循环语句

Jinja2模版的for循环不存在break和continue来判断循环的语句,这个是和Python最大的区别,另外jinja2中只有for循环,不存在while循环

from flask import Flask,render_template

app = Flask(__name__)
@app.route("/for")
def forx():
    books = [{
        "name":"三国演义",
        "author":"罗贯中",
        "price":100
    },{
        "name":"水浒传",
        "author":"施耐庵",
        "price":30
    }]
    return render_template("forxunhuan.html",books=books)

if __name__ == '__main__':
    app.run(debug=True,host="0.0.0.0",port=8000)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>for循环语言演示</title>
</head>
<body>
{% for book in books%}

<div>{{loop.index}}:书名:{{book.name}},作者:{{book.author}},价格:{{book.price}}</div>
{% endfor %}
</body>
</html>