flask 模版if 语句和for语句

if语句

格式:

{% if command %}
{% elif %}
{% else %}
{% endif %}

 

代码示例

flask_one.py

#encoding:utf-8
from flask import Flask,url_for,redirect,render_template

app = Flask(__name__)

@app.route(‘/<is_login>‘)
def index(is_login):

    if is_login == "1":        #模拟1为登陆成功
        user = {
            "aa":"test",
            ‘bbb‘:‘注销‘,
            ‘age‘:"11"
        }
        return render_template(‘index.html‘,users=user)
    else:
        return render_template(‘index.html‘)


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

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {% if users and users.age >10 %}        #这里的users为py文件里传递的user字典,users.age为py文件user字典里的age
        <a href="#">{{ users.aa }}</a>
        <a href="#">{{  users.bbb}}</a>
    {% else %}
        <a href="#">登陆</a>
        <a href="#">注册</a>
    {% endif %}
</body>
</html>

url入口:127.0.0.1/{1,0..}

 

for语句

格式:

{% for .. %}
{% endfor %}

 

代码实现:

flask_one.py

#encoding:utf-8
from flask import Flask,url_for,redirect,render_template

app = Flask(__name__)

@app.route(‘/‘)
def index():
    users = {
        ‘username‘:‘tsdf‘,
        ‘age‘:11
    }
    return render_template(‘index.html‘,user=users)
if __name__ == ‘__main__‘: app.run(debug=True)

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {% for k,v in user.items() %}        #for语句
        <p>{{ k }}----{{ v }}</p>
    {% endfor %}
</body>
</html>

 

代码示例:

 

flask_one.py

#encoding:utf-8
from flask import Flask,url_for,redirect,render_template

app = Flask(__name__)

@app.route(/)
def index():
    books = [
        {name:西游记,author:吴承恩,price:111},
        {name: 红楼梦, author: 曹雪芹, price: 121},
        {name: 水浒传, author: 施耐庵, price: 131},
        {name: 三国演义, author: 罗贯中, price: 141}
    ]
    return render_template(index.html,book=books)


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

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <table border="1">
        <thead>
            <th>书名</th>
            <th>作者</th>
            <th>价格</th>
        </thead>
        <tbody>
            {% for book in book %}        #for循环列表并打印字典里的内容
                <tr>
                    <td>{{ book.name }}</td>
                    <td>{{ book.author }}</td>
                    <td>{{ book.price }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>

</body>
</html>

 

技术分享图片

 

文章来自:https://www.cnblogs.com/FRESHMANS/p/8428565.html
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3