python-Flask(jinja2)语法:判断与循环

逻辑与循环

[TOC]

if 语句

语法:

{% if xxx %}
{% else %}
{% endif %}

例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    {% if user and user.age > 18 %}
        <a href="#">{{ user.username }}</a>
        <a href="#">注销</a>
    {% else %}
        <a href="#">登录</a>
        <a href="#">注册</a>
    {% endif %}
</body>
</html>
@app.route('/<is_login>/')
def index(is_login):
    if is_login:
        user = {
            'username' : u'站长',
            'age' : 22
        }
        return render_template('index.html', user= user)
        # 已经注册则传进去参数
    else:
        return render_template('index.html') 
        # 没有注册则直接渲染

for循环遍历

字典遍历:语法和python一样,可以使用items()keys()values()iteritems()iterkeys()itervalues()

{% for k,v in user.items() %}
    <p>{{ k }}:{{ v }}</p>
{% endfor %}
# for遍历字典
@app.route('/')
def index():
    # 定义一个字典
    user = {
        'username' : u'站长',
        'age' : 22
    }
    return render_template('index.html',user=user)

列表遍历:,语法与python一样

{% for website in websites %}
    <p>{{ website }}</p>
{% endfor %}
# for遍历列表
@app.route('/')
def index():
    websites = ['www.baidu.com','www.google.com'] 
    return render_template('index.html',websites=websites)

例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <p>综合运用列表和字典的模板文件</p>
    <table>
        <thead>
            <th>书名</th>
            <th>作者</th>
            <th>价格</th>
        </thead>
        <tbody>
            {% for book in books %}
                <tr>
                    <td>{{ book.name }}</td>
                    <td>{{ book.author }}</td>
                    <td>{{ book.price }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>
#encoding: utf-8
from flask import Flask,render_template

app = Flask(__name__)

@app.route('/')
def index():
    books = [
        {
            'name' : u'西游记',
            'author' : u'吴承恩',
            'price' : 88
        },
        {
            'name': u'三国演义',
            'author': u'罗贯中',
            'price': 98
        },
        {
            'name': u'红楼梦',
            'author': u'曹雪芹',
            'price': 89
        },
        {
            'name': u'水浒传',
            'author': u'施耐庵',
            'price': 101
        }
    ]

    return render_template('index.html', books=books)

if __name__ == '__main__':
    app.run(debug=True)
    原文作者:SmallPot_Yang
    原文地址: https://www.jianshu.com/p/8f797fc449e8
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞