flask 模版if 语句和for语句

Posted FRESHMANS

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>

 

redirect 传数据到模板语言(flash)

from flask import redirect,flash

@app.route(\'/register\',methods=[\'GET\',\'POST\'])
def register():
    if request.method == \'GET\':
        return render_template(\'register.html\')
    else:
        phone = request.form.get(\'phone\')
        uname = request.form.get(\'username\')
        pwd = request.form.get(\'password\')
        pwd1 = request.form.get(\'password1\')

        user = User.query.filter(User.phone == phone).first()

        if user is not None:
            return "用户已经存在"
        else:
            if phone == "" or uname == "":
                flash(\'手机号或者用户名不能为空\')
                return redirect(url_for(\'register\'))

            elif pwd != pwd1:
                flash(\'两次输入的密码不匹配\')
                return redirect(url_for(\'register\'))
            else:
                user = User(phone=phone,username=uname,password=pwd)
                db.session.add(user)
                db.session.commit()
                # user = User.query.filter(User.phone == phone).first()
                # print (user)
                return redirect(url_for(\'login\'))

 

模板语言:

{% extends \'common.html\' %}
{% block title %}
    注册
{% endblock %}

{% block head %}
    <link rel="stylesheet" href="{{ url_for(\'static\',filename=\'css/login_regist.css\') }}">
{% endblock %}

{% block body %}
<div class="form-container">
    <h4 style="text-align: center">注册</h4>
    <form action="" method="POST">

      <div class="form-group">
        <span><input type="text" class="form-control" id="exampleInputEmail1" placeholder="手机号" name="phone"></span>
      </div>
      <div class="form-group">
        <span><input type="text" class="form-control" id="exampleInputEmail1" placeholder="用户名" name="username"></span>
      </div>
      <div class="form-group">
        <span><input  type="password" class="form-control" id="exampleInputPassword1" placeholder="密码" name="password"></span>
      </div>
      <div class="form-group">
        <span><input  type="password" class="form-control" id="exampleInputPassword1" placeholder="重复密码" name="password1"></span>
      </div>

      <button type="submit" class="btn btn-block" onclick="tj()">立即注册</button>
    </form>
    <p>
        {% for message in get_flashed_messages() %}
            {{ message }}
        {% endfor %}
    </p>
</div>

{% endblock %}

 

 

代码示例:

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>

 

 自定义错误信息

@app.errorhandler(404)
def page_noe_found(error):
    return render_template(\'home/404.html\'),404

@app.errorhandler(500)
def page_noe_found(error):
    return render_template(\'home/500.html\'),500

 

以上是关于flask 模版if 语句和for语句的主要内容,如果未能解决你的问题,请参考以下文章

流程控制 for标签和if标签

SQL Select 语句的用法

flask学习:if判断语句

MATLAB for循环内if语句判断失败

flask模版继承和block

高效的 if 语句 / for 循环