「Flask筆記」 jinjia2 範本之控制語句,flask – jinja2範本之控制語句if語句語法{% if 判斷條件 %}.....{% elif 判斷條件 %}.....{% else %}.....{% endif %}{% if age == 18 %}
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>
聲明:本文為原創作品,版權歸作者所有。未經許可,不得轉載或用於任何商業用途。如若本站內容侵犯了原著者的合法權益,可聯繫我們進行處理。