<!--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>
示例:
# 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>