flask的for、if语法

for循环语法:

{% for 变量 in 可迭代对象 %}
for循环要做的任务
{% endfor %}

if语句语法:

{% if 条件 %}
    条件为true
{% else %} 
    条件为false
{% endif %} 

loop语法 for循环中使用 可以添加索引:

{{ loop.index }}  序号是从1开始
{{ loop.index0 }} 序号是从0开始

{{ loop.revindex }} 序号是倒序 最后结束是1
{{ loop.revindex0 }} 序号是倒序 最后结束是0

案例:app.py

from flask import Flask
from flask import make_response, request, render_template,redirect,url_for
import setting,json

app = Flask(__name__)
app.config.from_object(setting)

@app.route('/show')
def show():
    girls = ["yanan","zhouqiang","nike","puma"]
    users = [
        {"name":"zhouqiang","age":18,"gender":"man","address":"anhuihefei"},
        {"name": "zhouqiang", "age": 18, "gender": "man", "address": "anhuihefei"},
        {"name": "zhouqiang", "age": 18, "gender": "man", "address": "anhuihefei"},
        {"name": "zhouqiang", "age": 18, "gender": "man", "address": "anhuihefei"},
        {"name": "zhouqiang", "age": 18, "gender": "man", "address": "anhuihefei"},
        {"name": "zhouqiang", "age": 18, "gender": "man", "address": "anhuihefei"},
        {"name": "zhouqiang", "age": 18, "gender": "man", "address": "anhuihefei"}

    ]
    return render_template('test.html',users = users)

# 如果没有找到匹配的,会以空白字符串填充
if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000)

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .a{
            color:red;
        }
    </style>
</head>
<body>
<div>用户信息展示</div>
<ul>
{% for girl in girls %}
    {% if girl|length >=5 %}
        <li class="a"> {{ girl }} </li>
    {% else %}
        <li> {{ girl }} </li>
    {% endif %}
{% endfor %}
</ul>

<table>
    {% for user in users %}
        <tr {% if loop.last %} style="background-color: deeppink" {% endif %}> #判断是否是最后一行,如果是就添加样式
            <td>{{ loop.index }}</td>
            <td>{{ loop.index0 }}</td>
            <td>{{ user.name }}</td>
            <td>{{ user.age }}</td>
            <td>{{ user.gender }}</td>
            <td>{{ user.address }}</td>
        </tr>
    {% endfor %}
</table>

</body>
</html>

 

posted @ 2021-09-09 15:58  fat_girl_spring  阅读(350)  评论(0编辑  收藏  举报