[Flask] Python Flask 框架(二)

[Jinjia2] 模板渲染,模板訪問(wèn)對(duì)象屬性,過(guò)濾器屬性,控制語(yǔ)句,

項(xiàng)目目錄結(jié)構(gòu):
Flask-learning
        static
        templates
            blog_detail.html
            control.html
            filter.html
            index.html
      app.py

app.py 
------------------------------------------------------------------
from flask import Flask , request ,render_template
from datetime import datetime

app = Flask(__name__)

# 自定義過(guò)濾器
def data_format(value,format = "%Y-%d-%m "):
    return value.strftime(format)
app.add_template_filter(data_format,"dformat")

class User:
    def __init__(self,username,email):
        self.username = username
        self.email = email

@app.route('/')
def hello_world():
    user = User(username="li", email= "123@qq.com")
    person  = {
        "name" :"zhangsan",
        "password" : "123"
    }
    return  render_template("index.html" , user = user , person = person)

@app.route("/blog/<id>")
def blog_detail(id):
    return render_template("blog_detail.html",blog_id = id)

@app.route("/fiter")
def filter():
    user = User(username="li", email= "123@qq.com")
    mytime = datetime.now()
    books = [{
        "name" : " sanguo",
        "author" : "luoguanzhong"
    },{
        "name": " shuihu",
        "author": "shinaian"
    },]
    return render_template("fiter.html" , user =user,mytime = mytime,books =books )

@app.route("/control")
def control():
    age = 17
    books = [{
        "name": " sanguo",
        "author": "luoguanzhong"
    }, {
        "name": " shuihu",
        "author": "shinaian"
    }, ]
    return render_template("control.html" ,age = age ,books =books )

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

------------------------------------------------------------

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首頁(yè)</title>
</head>
<body>
This is Main page!
{{user.username}}
{{user.email}}
{{person.name}}
</body>
</html>

---------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>過(guò)濾器</title>
</head>
<body>
{{user.username}} - {{user.username | length }}
<div> {{ mytime  | dformat}} </div>
</body>
</html>


--------------------------------------------------------------------------

comtrol.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>控制語(yǔ)句</title>
</head>
<body>

{% if age > 18 %}
    <div> 已經(jīng)成年</div>
{% elif age < 18 %}
    <div> 未成年</div>
{% else %}
    <div> 成年</div>
{% endif %}

{% for book in books %}
    <div>{{book.name}} , {{ book.author }}</div>
{% endfor %}
</body>
</html>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容