python-web框架Flask-(五)jinjia2模板

渲染模板:

在flask中渲染模板很簡單!!!

首先導入render_template模塊,然後把html文件放入templates文件夾,在視圖函數中,使用render_template(  ) 函數來渲染模板即可:

from flask import render_template
@app.route('/')
def fn():
    return render_template('tempalte_1.html')

flask會自動去templates文件夾尋找相對應的html文件。

注意:如果HTML文件是在templates文件夾下 別的的文件夾下,渲染時應帶上文件路徑:

··· 
return render_template('file/xxx.html')
···

 

模板傳參:

方式一:以關鍵字參數(等式)傳遞參數

from flask import render_template
@app.route('/')
def fn():
    return render_template('html.html',name='lxc')

方式二:以字典形式傳參(適用於參數多的情況下)

from flask import render_template
@app.route('/')
def fn():
    dict = {'name':'lxc','age':20,'height':175}
    return render_template('html.html',**dict)
<!-- html文件 -->
··· ···
<body>
    <h1>hello,{{name}},年齡是{{age}},身高是:{{height}}</h1>
</body>
··· ···

模板中的if語句:

與python語法一樣,if判斷條件,條件成立執行下邊對應html代碼塊,只不過在結束時,添加 endif 結束,來表名該if語句結束了。

寫法:

{% if Boolean %}
    <h1>xxx</h1>
{% else %}
    <h1>xxx</h1>
{% endif %}

來一個簡單應用:路徑參數爲1時,顯示:姓名與註銷;否則顯示:親,請登錄! 和 註冊

@app.route('/<is_login>')
def fn(is_login):
    if is_login == '1':
        info = {'name':'呂星辰','age':20}
        return render_template('html.html',**info)
    else:
        return render_template('html.html')
# html.html文件
<body>
    {% if name %} <!-- 判斷是否有name屬性,也可以判斷是否有age屬性-->
        <h1>hello,{{name}},年齡{{age}}</h1>
        <h1>註銷</h1>
    {% else %}
        <h1>親,請登錄</h1>
        <h1>註冊賬號</h1>
    {% endif %}
</body>

當然也可以,在if條件語句中比較:

# html.html文件
<body>
    {% if name and age > 18 %} <!-- 判斷是否有name屬性,也可以判斷是否有age屬性-->
        <h1>hello,{{name}},年齡{{age}}</h1>
        <h1>註銷</h1>
    {% else %}
        <h1>親,請登錄</h1>
        <h1>註冊賬號</h1>
    {% endif %}
</body>

 

模板中的for循環:

循環字典及列表,與if語句類似:

# 循環字典
{% for k,v in xxx.items() %}
    <h1>{{k}}:{{v}}</h1>
{% endfor %}

# 循環列表
{% for item in xxx %}
    <h1>{{item}}</h1>
{% endfor %}

小demo:

@app.route('/')
def fn():
        info = {'name':'呂星辰','age':20}
        return render_template('html.html',info=info)
# html模板
<body>
    {% for k,v in info.items() %}
        <h1>{{k}}:{{v}}</h1>
    {% endfor %}
</body>

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章