在`jinja2`中的`for`循环,跟`python`中的`for`循环基本上是一模一样的。也是`for...in...`的形式。并且也可以遍历所有的序列以及迭代器。但是唯一不同的是,`jinja2`中的`for`循环没有`break`和`continue`语句。
在‘Jinja’中的‘for’循环还包含以下变量,可以用来获取当前的遍历状态:
- loop.index :当前迭代的索引(从1开始)
- loop.index0 :当前迭代的索引(从0开始)
- loop.first :是否是第一次迭代,返回True或者False
- loop.last :是否是最后一次迭代,返回True或者False
- loop.length :序列的长度
1、遍历列表
<ul>
{% for user in users|reverse %}
<li>{{ user }}</li>
{% else %}
<li>沒有值</li>
{% endfor %}
</ul>
2、遍历字典
<table>
<thead>
<tr>
<th>用户名</th>
<th>年龄</th>
<th>国家</th>
</tr>
</thead>
<tbody>
<tr>
{% for key in person.keys() %}
<td>{{ key }}</td>
{% endfor %}
</tr>
<tr>
{% for value in person.values() %}
<td>{{ value }}</td>
{% endfor %}
</tr>
</tbody>
</table>
3、遍历列表中的字典
<table>
<thead>
<tr>
<th>序号</th>
<th>书名</th>
<th>作者</th>
<th>价格</th>
<th>总数</th>
</tr>
</thead>
<tbody>
{% for book in books %}
{% if loop.first %}
<tr style="background: red;">
{% elif loop.last %}
<tr style="background: pink;">
{% else %}
<tr>
{% endif %}
<td>{{ loop.index0 }}</td>
<td>{{ book.name }}</td>
<td>{{ book.author }}</td>
<td>{{ book.price }}</td>
<td>{{ loop.length }}</td>
</tr>
{% endfor %}
</tbody>
</table>
完整的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>知了for循环</title>
</head>
<body>
<ul>
{% for user in users|reverse %}
<li>{{ user }}</li>
{% else %}
<li>沒有值</li>
{% endfor %}
</ul>
<table>
<thead>
<tr>
<th>用户名</th>
<th>年龄</th>
<th>国家</th>
</tr>
</thead>
<tbody>
<tr>
{% for key in person.keys() %}
<td>{{ key }}</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>
<th>总数</th>
</tr>
</thead>
<tbody>
{% for book in books %}
{% if loop.first %}
<tr style="background: red;">
{% elif loop.last %}
<tr style="background: pink;">
{% else %}
<tr>
{% endif %}
<td>{{ loop.index0 }}</td>
<td>{{ book.name }}</td>
<td>{{ book.author }}</td>
<td>{{ book.price }}</td>
<td>{{ loop.length }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
from flask import Flask, render_template
import config
app = Flask(__name__)
app.config.from_object(config)
@app.route('/')
def index():
context = {
'users': ['bj1', 'bj2', 'bjo3'],
'person': {
'username': 'bj',
'age': 18,
'country': 'US'
},
'books': [
{
'name': '三国演义',
'author': '罗贯中',
'price': 40
}, {
'name': '西游记',
'author': '吴承恩',
'price': 69
}, {
'name': '红楼梦',
'author': '曹雪芹',
'price': 70
}, {
'name': '水浒传',
'author': '施耐庵',
'price': 89
}
]
}
return render_template('index.html', **context)
if __name__ == '__main__':
app.run()