是否有一种方法可以在 Jinja2 中迭代列表,从而可以在单次迭代中访问第 n 个和第 (n+1) 个元素?
{% for x in my_list %}
<!-- print the current and the (current+1) -->
{{x}}, {{x+1}} <-- this is wrong but hopefully highlights the problem
{% endfor %}
此外,for 循环是否允许“步长”增量?
最佳答案
Jinja 有一个 loop.index
您可以使用该变量来访问列表中的下一个值:
@app.route('/')
def index():
return render_template_string("""
<body>
{% for x in my_list %}
<p>
{{ x }} {{ my_list[loop.index] }}<br>
</p>
{% endfor %}
</body>
""", my_list=range(10))
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9
关于python - 获取 Jinja for 循环中的当前值和下一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38509802/