from flask import Flask,render_template app = Flask(__name__) app.config.update( DEBUG = True, ) @app.route('/') def index(): context = { 'user':['老男孩是垃圾1','老男孩是垃圾2','老男孩是垃圾3'], 'person':{ 'name':"xiaowu", 'age': 18, 'salary' : 10000, }, 'books':[ { 'name':'三国演义', 'author':'罗贯中', 'price':110 }, { 'name': '红楼梦', 'author': '曹雪芹', 'price': 109 }, { 'name': '西游记', 'author': '吴承恩', 'price': 111 }, { 'name': '水浒传', 'author': '施耐庵', 'price': 112 }, ] } return render_template('for_used.html',**context) if __name__ == '__main__': app.run()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>for模板使用</title> <style> th,td{ border: solid 1px silver } </style> </head> <body> <h1>for循环的模板使用</h1> <!--reverse过滤器,反转列表元素--> {% for foo in user|reverse %} <li>{{ foo }}</li> <!--user中没有任何值,是空列表--> {% else %} <p>列表中没有任何值</p> {% endfor %} <table style="border-spacing: 1px;"> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>薪水</th> </tr> </thead> <tbody> <tr> <td>{{ person.name }}</td> <td>{{ person.age }}</td> <td>{{ person.salary }}</td> </tr> </tbody> </table> <table style="border-spacing: 1px;"> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>薪水</th> </tr> </thead> <tbody> <tr> {% for key,value in person.items() %} <td>{{ value }}</td> {% endfor %} </tr> <!--下面的写法--> <tr> {% for value in person.values()%} <td>{{ value }}</td> {% endfor %} </tr> </tbody> </table> <!---------------------------------------------------------------------> <table> <thead> <tr> <th>序号</th> <th>书名</th> <th>作者</th> <th>价格</th> </tr> </thead> <tbody> {% for book in books %} <!--loop.first,看是否是第一迭代,是True,不是false--> {% if loop.first %} <tr style="background: red"> <!--loop.last,看是否是最后一次迭代,是True,不是false--> {% elif loop.last %} <tr style="background: green"> {% else %} <tr> {% endif %} <!---loop.index 从1开始计数,计数列表有多少元素--> <!---loop.index0 从0开始技术--> <td>{{ loop.index }}</td> <td>{{ book.name }}</td> <td>{{ book.author }}</td> <td>{{ book.price }}</td> {# <td style="row-span: 4">#} {# <!--loop.length的列表的长度-->#} {# <h4>总数:{{ loop.length }}</h4>#} {# </td>#} </tr> {% endfor %} </tbody> <tfoot> <tr> <td> <p style="font-weight: bold;font-size: 12px">总数</p> </td> <!--rowspan中必须指定要合并的列数目,是两行还是三行等等--> <!--colspan中必须指定要合并的列数目,是两列还是三列等等--> <td colspan="3" style="text-align: center"> 4 </td> </tr> </tfoot> </table> </body> </html>