for循环语句
1、使用for循环遍历列表
# 后端代码
@app.route('/')
def index():
articles = {
'titles': ['文章标题1', '文章标题2', '文章标题3']
}
return render_template('index.html', **articles)
# 前端代码
{% for title in titles %}
<li>{{ title }}</li>
{% else %}
没有文章
{% endfor %}
2、使用for循环遍历字典
# 后端代码
@app.route('/')
def index():
articles = {
'shares': {
'baidu': '百度',
'google': '谷歌',
'sogou': '搜狗'
}
}
return render_template('index.html', **articles)
# 前端代码
# 遍历字典的键
{% for share in shares %}
<li>{{ share }}</li>
{% endfor %}
#遍历字典的值
{% for share in shares.values() %}
<li>{{ share }}</li>
{% endfor %}
3、常用的for循环内置变量
变量 |
描述 |
loop.index |
从1开始循环输出索引 |
loop.index0 |
从0开始循环输出索引 |
loop.first |
是否为序列的第一个元素 |
loop.last |
是否为序列的最后一个元素 |
loop.length |
输出序列的长度 |