Jinja2過濾器的使用、控制語句示例詳解
1.過濾器的使用
1.過濾器和測試器
在Python中,如果需要對某個變量進(jìn)行處理,我們可以通過函數(shù)來實現(xiàn)。在模板中,我們則是通過過濾器來實現(xiàn)的。過濾器本質(zhì)上也是函數(shù),但是在模板中使用的方式是通過管道符號(|)來調(diào)用的。例如有個字符串類型變量name,想要獲取他的長度,則可以通過 {name[length}}來獲取,Jinja2會把name當(dāng)做第一個參數(shù)傳給length過濾器底層對應(yīng)的函數(shù)。length是Jinja2內(nèi)置好的過濾器,Jinja2中內(nèi)置了許多好用過濾器,如果內(nèi)置過濾器不滿足需求,我們還可以自定義過濾器。我們先來學(xué)習(xí)下如何自定義過濾器,讀者明白了過濾器的原理后,再去學(xué)習(xí)Jinja2內(nèi)置過濾器就更能得心應(yīng)手了。
2.過濾器
templates/filter.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>過濾器使用demo</title>
</head>
<body>
{{ user.username}}-{{ user.username|length }}
</body>
</html>app.py
# render_template 渲染模板
from flask import Flask, render_template
app = Flask(__name__)
class User:
def __init__(self, username, email):
self.username = username
self.email = email
@app.route("/filter")
def filter_demo():
user = User(username="小程xxx", email="xxx@qq.com")
return render_template("filter.html",user=user)
if __name__ == '__main__':
app.run()效果

3.自定義過濾器
過濾器本質(zhì)上是 Python的函數(shù),他會把被過濾的值當(dāng)做第一個參數(shù)傳給這個函數(shù),函數(shù)經(jīng)過一些邏輯處理后,再返回新的值。在過濾器函數(shù)寫好后,可以通過@app.template_ filter裝飾器或者是app.add_template_filter函數(shù)來把函數(shù)注冊成Jinja2能用的過濾器。這里我們以注冊一個時間格式化的過濾器為例,來說明下自定義過濾器的方法。
app.py
# render_template 渲染模板
from flask import Flask, render_template
from datetime import datetime
app = Flask(__name__)
# strftime:根據(jù)區(qū)域設(shè)置格式化本地時間
# format:格式化
def datetime_format(value,format="%Y年%m月%d日 %H:%m"):
return value.strftime(format)
app.add_template_filter(datetime_format,"dformat")
class User:
def __init__(self, username, email):
self.username = username
self.email = email
# filter:過濾器
@app.route("/filter")
def filter_demo():
user = User(username="小程xxx", email="xxx@qq.com")
mytime=datetime.now()
return render_template("filter.html",user=user,mytime=mytime)
if __name__ == '__main__':
app.run()上面我們定義了一個datetime_formt的函數(shù),第一個參數(shù)是需要被處理的值,第二個參數(shù)是時間的格式,并且指定了一個默認(rèn)值。然后下面通過app.add_template_filter,將datetime_format函數(shù)注冊成了過濾器,并且這個過濾器的名字,叫做dformat。那么以后在模板文件中,就可以這樣類似這樣使用了:
templates/filter.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>過濾器使用demo</title>
</head>
<body>
<div>{{ user.username}}-{{ user.username|length }}</div>
<div>{{ mytime|dformat }}</div>
</body>
</html>效果

2.控制語句
1.if
app.py
# render_template 渲染模板
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/control")
def control_statement():
age=17
return render_template("control.html",age=age)
if __name__ == '__main__':
app.run()templates/control.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% if age>18 %}
<div>您已經(jīng)滿118歲,可以進(jìn)入網(wǎng)吧!</div>
{% elif age==18 %}
<div>您剛滿18歲,需要父母陪同才能進(jìn)入!</div>
{% else %}
<div>您未滿18歲,不能進(jìn)入網(wǎng)吧!</div>
{% endif %}
</body>
</html>注:
- 可以注意到if語句結(jié)束后,需要加一個endif來關(guān)閉if代碼塊。這個跟python是有點不同的。
- Jinja2中的代碼縮進(jìn)只是為了更加方便閱讀。任何縮進(jìn)都不是必須的。

2.for
app.py
# render_template 渲染模板
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/control")
def control_statement():
age = 17
books = [{
"name": "三國演義",
"author": "羅貫中"
},{
"name": "水滸傳",
"author": "施耐庵"
}
]
return render_template("control.html", age=age,books=books)
if __name__ == '__main__':
app.run()templates/control.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for book in books %}
<div>圖書名稱:{{ book.name }},圖書作者:{{ book.author }}</div>
{% endfor %}
</body>
</html>
相關(guān)文章
淺談Keras中shuffle和validation_split的順序
這篇文章主要介紹了淺談Keras中shuffle和validation_split的順序,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Python使用asyncio異步時的常見問題總結(jié)
這篇文章主要為大家整理了開發(fā)人員在?Python?中使用?asyncio?時提出的常見問題以及解決方法,文中的示例代碼講解詳細(xì),感興趣的可以學(xué)習(xí)一下2023-04-04
python將字母轉(zhuǎn)化為數(shù)字實例方法
在本篇文章里小編給大家整理的是關(guān)于python如何將字母轉(zhuǎn)化為數(shù)字的相關(guān)實例內(nèi)容,有需要的朋友們可以學(xué)習(xí)下。2019-10-10

