Bootstrap

Flask模板_循环结构

Flask模板_循环结构

一.介绍

for…in… for循环可以遍历任何一个序列包括列表、字典、元组。并且 可以进行反向遍历。

二.实例

html源码:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>循环结构</title>
</head>
<body>
    <h2>正向遍历列表</h2>
    {% for it in items %}
        <span>{{ it }}</span>&nbsp;&nbsp;&nbsp;
    {% endfor %}
    <br>
    <h2>反向遍历列表</h2>
    {% for it in items | reverse %}
        <span>{{ it }}</span>&nbsp;&nbsp;&nbsp;
    {% endfor %}
    <br>
    <h2>遍历字典</h2>
    {% for x in udict.keys() %}
        <span>{{ x }}</span>&nbsp;&nbsp;&nbsp; 
    {% endfor %}
    <br>
    {% for x in udict.values() %}
        <span>{{ x }}</span>&nbsp;&nbsp;&nbsp; 
    {% endfor %}
    <br>
    {% for x in udict.items() %}
        <h5>{{ x }} === {{ loop.index }} === {{ loop.index0 }} === {{ loop.first }} === {{ loop.last }} === {{ loop.lenght }}</h5>
    {% endfor %}

    <h2>实战:99乘法表</h2>
    <div style="color: aqua;">
        <table border="1">
            {% for i in range(1,10) %}
            <tr>
                {% for j in range(1, i+1) %}
                    <td>{{ i }} * {{ j }} = {{ i * j }}</td>
                {% endfor %}
            </tr>
            {% endfor %}
        </table>
    </div>
</body>
</html>
python源码:
#coding=utf-8

from flask import Flask,render_template

app = Flask(__name__,template_folder='htmls')

@app.route('/')
def show():
    items = ['C','C++11','Python','Javescript','html5','CSS3','jQuery','Java','php']
    udict = {'name':'hh','age':20,'height':'180cm','weight':'60kg'}
    return render_template('循环结构.html',items=items,udict=udict)

if __name__ == '__main__':
    app.run(debug=True)

在这里插入图片描述

注:
如果觉得笔记有些问题,麻烦在百忙之中在评论中指正,或提出建议!另外,如果觉得这份笔记对你有所帮助,麻烦动动发财的小手手点一波赞!
;