Flask(8) - jinja2模板使用(if语句和for循环)

mac2024-08-18  65

if判断

模板中的if判断和python判断类似,可以使用“<、>、>=、<=、==、!=”来进行判断 也可以使用“and 、or、not”判断操作 # app.py @app.route('/') def hello_world(): res = { "name": "呵呵", "age": 9, } return render_template("index.html", **res)

 

<!--index.html--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> {% if name == "呵呵" %} <p>{{ age }}</p> {% else %} <p>age不存在</p> {% endif %} {% if age >= 10 %} <p>{{ name }}</p> {% else %} <p>name不存在</p> {% endif %} </body> </html>

for循环

for使用:for循环和python相同,for...in... for循环可以遍历任何一个序列,包括数组、字典、元组

示例:

# app.py from flask import Flask, render_template app = Flask(__name__) @app.route("/index/") def index(): res = { "name": ["name1", "name2", "name3"], "name2": { "username": "hahaha", "age": "20", }, "books": [ { "name": "西游记", "auth": "吴承恩", "price": 100 }, { "name": "红楼梦", "auth": "曹雪芹", "price": 120 } ] } return render_template("index.html", **res) if __name__ == '__main__': app.run(debug=True) <!DOCTYPE html> <html lang="zh-en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>index</title> </head> <body> <!--for循环--> {% for name1 in name %} <p>{{ name1 }}</p> {% endfor %} <!-- for循环字典 --> <table> <thead> <tr> <th>用户名</th> <th>年龄</th> </tr> </thead> <tbody> <tr> {% for key,value in name2.items() %} <td>{{ value }}</td> {% else %} <p>没有内容!!!</p> {% endfor %} {# <td>{{ name2.username }}</td>#} {# <td>{{ name2.age }}</td>#} </tr> </tbody> </table> <!-- for循环变量使用 --> <table> <thead> <tr> <th>序列长度</th> <th>是否最后一次迭代</th> <th>是否第一次迭代</th> <th>序号</th> <th>序号0</th> <th>书名</th> <th>作者</th> <th>价格</th> </tr> </thead> <tbody> {% for book in books %} <tr> <td>{{ loop.length }}</td> <!--序列长度--> <td>{{ loop.last }}</td> <!--是否最后一次迭代,是返回True--> <td>{{ loop.first }}</td> <!--是否第一次迭代,是返回True--> <td>{{ loop.index }}</td> <!--从一开始--> <td>{{ loop.index0 }}</td> <!--从零开始--> <td>{{ book.name }}</td> <td>{{ book.auth }}</td> <td>{{ book.price }}</td> </tr> {% endfor %} </tbody> </table> </body> </html>

九九乘法表

<!--使用for循环和if写九九乘法表--> <!DOCTYPE html> <html lang="zh-en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>index</title> </head> <body> <table> <tbody> <!--循环取数值1-9,range顾头不顾尾--> {% for x in range(1,10) %} <tr> {% for y in range(1,10) %} {% if y <= x %} <th>{{ y }}x{{ x }}={{ x*y }}</th> {% endif %} {% endfor %} </tr> {% endfor %} </tbody> </table> </body> </html>

 

最新回复(0)