1. 程式人生 > >flask中jinjia2模板引擎使用詳解4

flask中jinjia2模板引擎使用詳解4

編程語言 Python

接上文

For循環

和其它編程語言一樣,for用來編輯列表中的項。下面以一個例子來說明for在flask的jinjia2模板中的使用。

創建一個模板list.html

代碼如下:

{% %}
{% %}
     {% %}
     <>{{ }}</>
     {% %}
{% %}

在code.py中添加url規則

@app.route()
renderList():
     users = [,,]
     render_template(,users = users)

運行效果如下:

技術分享圖片

變量

描述

loop.index

當前循環叠代的次數(從 1 開始)

loop.index0

當前循環叠代的次數(從 0 開始)

loop.revindex

到循環結束需要叠代的次數(從 1 開始)

loop.revindex0

到循環結束需要叠代的次數(從 0 開始)

loop.first

如果是第一次叠代,為 True 。

loop.last

如果是最後一次叠代,為 True 。

loop.length

序列中的項目數。

loop.cycle

在一串序列間期取值的輔助函數。見下面的解釋。

我們以上面的例子來說明其中幾個變量的使用

{% %}
<>{{ }},"first:"{{ .}},"last:"{{ .}},"length:"{{ .}},"index:"{{ .}},"index0:"{{ .}},"revindex:"{{ .}},"revindex0:"{{ .}},"cycle:"{{ .(,) }}</>
{% %}

運行效果:

技術分享圖片

通過if內聯過濾來篩選數據

Jinjia2模板中的循環不支持break和continue語法。

可以通過if內聯過濾來篩選數據,舉例:

<>長度大於6的:</>
    {% | | >6 %}
   <>{{ }},"first:"{{ .}},"last:"{{ .}},"length:"{{ .}},"index:"{{ .}},"index0:"{{ .}},"revindex:"{{ .}},"revindex0:"{{ .}},"cycle:"{{ .(,) }}</>
   {% %}

運行效果:

技術分享圖片

Li si因長度小於6,未被顯示出來

使用else來處理空列表

當一個for循環的數據源為空時,可以用else進行替換方案顯示,比如我們for一個不存在的對象items,然後用else作判斷:

<>空列表</>
{% %}
<>{{ }}</>
{% %}
     <>未找到數據 </>
{% %}

運行效果:

技術分享圖片

遞歸調用for循環

通過在for中使用recursive關鍵字,並且在需要遞歸的地方使用loop方法就可以實現遞歸調用for循環

引用官方的例子如下:

<ul class="sitemap">
{%- for item in sitemap recursive %}
    <li><a href="{{ item.href|e }}">{{ item.title }}</a>
    {%- if item.children -%}
        <ul class="submenu">{{ loop(item.children) }}</ul>
    {%- endif %}</li>
{%- endfor %}
</ul>


本源代碼:鏈接:https://pan.baidu.com/s/1wRG-W1kY0o1z2zi1UTmRhQ 密碼:yrzz

flask中jinjia2模板引擎使用詳解4