内容简介:语法语法并且'Jinja2'中的'for'循环还包含以下遍历,可以用来获取当前的遍历状态:
flask -- jinja2模板之控制语句
if语句
语法
{% if 判断条件 %}
.....
{% elif 判断条件 %}
.....
{% else %}
.....
{% endif %}
{% if age == 18 %}
<p>成年了</p>
{% elif age < 18 %}
<p>未成年</p>
{% else %}
<p>....</p>
{% endif %}
for循环语句
语法
{% for _ in 迭代对象 %}
....
{% else %}
{# 如果没有遍历对象则显示的内容 #}
....
{% endif %}
并且'Jinja2'中的'for'循环还包含以下遍历,可以用来获取当前的遍历状态:
loop.index
:当前迭代的索引(从 1
开始)
loop.index0
:当前迭代的索引(从 0
开始)
loop.first
:是否是第一次迭代,返回 True
或者 False
loop.last
:是否是最后一次迭代,返回 True
或者 False
loop.length
:序列的长度
另外,不可以使用 continue
和 break
表达式来控制循环的执行
<table border="1">
<tbody>
<thead>
<tr>
<th>书名</th>
<th>作者</th>
<th>价格</th>
<th>数量</th>
</tr>
{% for book in books %}
{% if loop.first %}
<tr style="background: red">
{% elif loop.last %}
<tr style="background:green">
{% elif loop.index==3 %}
<tr style="background: pink;">
{% else %}
<tr>
{% endif %}
<td>{{ book.name }}</td>
<td>{{ book.author }}</td>
<td>{{ book.price }}</td>
<td>{{ loop.length }}</td>
</tr>
{% endfor %}
</thead>
</tbody>
</table>
for循环输出九九乘法表
<table border="1">
<tbody>
{% for x in range(1,10) %}
<tr>
{% for y in range(1,x + 1 ) %}
<td>{{ x }} * {{ y }} = {{ x*y }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
以上所述就是小编给大家介绍的《「Flask笔记」 jinjia2 模板之控制语句》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- Word 模板引擎 poi-tl V1.7.1 发布,支持条件和循环语句
- MySQL 建表语句转 PostgreSQL 建表语句全纪录
- Go语言开发-过程式编程-通信和并发语句-Select语句
- SQL语句优化之JOIN和LEFT JOIN 和 RIGHT JOIN语句的优化
- Python 条件语句
- Python 循环语句
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。