Flask初級(七)flash模板循環,判斷


Project name :Flask_Plan

templates:templates

static:static

繼續前面的代碼

修改Flask_Plan.py

@app.route('/')
def hello_world():
    plan = [
        {
            'date':'20171212',
            'train':'T198',
            'track':'8'
        } ,
        {
            'date':'20171212',
            'train':'T199',
            'track':'9'
        } ,
        {
            'date':'20171212',
            'train':'T197',
            'track':'7'
        } ,
        {
            'date':'20171212',
            'train':'T196',
            'track':'6'
        }
    ]

    return render_template('plan.html', plans = plan)
View Code

修改templates/plan.html 

{% extends 'base.html' %}
{% block main2 %}
    <hr>
    {% for plan in plans %}
        {{ plan.date }}
        {{ plan.train }}
        {{ plan.track }}
        <br>
    {% endfor %}
{% endblock %}
View Code

我們在視圖函數中定義了一個嵌套字典的列表,並以plans的列表名傳入了模板plan.html

在模板中使用

{%  for plan in plans%}

{% end for%}

來創建循環,循環輸出列表當中的字典的值。

 

有了循環,也要有判斷

修改templates/plan.html 

{% extends 'base.html' %}
{% block main2 %}
    <hr>
    {% for plan in plans %}
        {{ plan.date }}
        {{ plan.train }}
        {% if plan.track == '8' %}
            8888
        {% elif plan.track =='9' %}
            9999
        {% else %}
            {{ plan.track }}
        {% endif %}
        <br>
    {% endfor %}
{% endblock %}
View Code

{% if plan.track == '8' %}
8888
{% elif plan.track =='9' %}
9999
{% else %}
{{ plan.track }}
{% endif %}

這樣的格式來使用判斷。

基本和python中一樣。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM