「Flask笔记」 jinjia2 模板之控制语句

栏目: Python · 发布时间: 5年前

内容简介:语法语法并且'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 :序列的长度

另外,不可以使用 continuebreak 表达式来控制循环的执行

<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 模板之控制语句》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Data Structures and Algorithms with JavaScript

Data Structures and Algorithms with JavaScript

Michael McMillan / O'Reilly Media / 2014-2-22 / USD 28.51

If you’re using JavaScript on the server-side, you need to implement classic data structures that conventional object-oriented programs (such as C# and Java) provide. This practical book shows you how......一起来看看 《Data Structures and Algorithms with JavaScript》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

SHA 加密
SHA 加密

SHA 加密工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具