一、Flask模板簡介
模板是一個web開發必備的模塊。因爲我們在渲染一個網頁的時候,並不是只渲染一個純文本字符串,而是需要渲染一個有富文本標籤的頁面。這時候我們就需要使用模板了。在Flask中,配套的模板是Jinja2,這個模板非常的強大,並且執行效率高。
# 模板文件自動更新
app.config['TEMPLATES_AUTO_RELOAD'] = True
jinjia2通過 render_template 將模板的前端代碼渲染到頁面中
前端代碼放在一個新的文件夾中,文件夾命名爲 templates
對前端代碼的路徑有特殊需求,需要對 template_folder 重新賦值
app = Flask(name, template_folder=r"./other")
模板中的註釋 {# #}
方法一: render_template 直接傳遞參數
# 在視圖函數中
return render_template("index.html", username="邏輯教育", age=18)
模板中添加:
<h1>{{ username }}</h1>
<h2>{{ age }}</h2>
方法二:render_template 的參數 context=參數名 進行傳參
# 在視圖函數中
# 定義一個字典
context = {
"username": "邏輯教育",
"age": 18
}
return render_template("index.html", context=context)
模板中添加:
<!-- -->
<h1>{{ context.username }}</h1>
方法三:render_template 參數爲 **context
視圖函數中 render_template 的參數 context=context 改成 **context(這裏相當於"username"= “邏輯教育”)
模板中和方法一的代碼一樣
context = {
"username": "邏輯教育",
"age": 18,
"books": {
"Python": 33,
"Java": 23,
"PHP": 25
}
}
return render_template("index.html", context=context)
<!-- 字典嵌套取值 -->
<h4>{{ books }}</h4> 這種方式會直接將整個字典在頁面中顯示
<h4>{{ books.Python }}</h4> 方法一,推薦使用
<h4>{{ books['Python'] }}</h4> 方法二
"book": ["Python", "PHP", "Java"]
return render_template("index.html", **context)
<!-- 列表取值 -->
<!-- 下標從0開始 -->
<h4>{{ book.2 }}</h4> 方法一,推薦使用
<h4>{{ book[1] }}</h4> 方法二
二、模板過濾器
過濾器是通過管道符號(|)進行使用的,例如:{{ name|length }},將返回name的長度。過濾器相當於是一個函數,把當前的變量傳入到過濾器中,然後過濾器根據自己的功能,再返回相應的值,之後再將結果渲染到頁面中。
返回一個數值的絕對值。
context = {
'username': "Emily",
'age': -19, # 這裏的19應該是數字而不是字符串
}
return render_template("index.html", **context)
<p>{{ username }}</p>
<p>{{ age|abs }}</p>
如果當前變量沒有被定義,則會使用參數中的值來代替。
@@@@@@@
原理是通過Python的布爾值進行判斷是否爲false
也就是當value 爲空字符串、None、空的列表,都是不使用默認值
None–>None
空字符串、空列表–>顯示爲空
<p>{{ name|default('這個人很懶,並沒有寫任何的簽名...') }}</p>
"es": "<script>alert('hello');</script>"
# 字典的其中一個元素
# js代碼代表彈出小窗口
方法一
<!-- 自動轉義 -->
<!-- 關閉轉義 -->
{% autoescape off %}
<p>{{ es }}</p>
{% endautoescape %}
方法二
<!-- 標記這個字符串是安全 -->
<p>{{ es|safe }}</p>
返回一個序列或者字典的長度。
<p>{{ book|length }}</p>
格式化字符串。
{{ "%s" - "%s"|format('Hello?',"Foo!") }}
將輸出:Helloo? - Foo!
返回一個序列的第一個元素。
- last
返回一個序列的最後一個元素。
- length
返回一個序列或者字典的長度。
length 可以和前面兩個參數配合使用
<p>{{ books|first }}</p>
<p>{{ books|last }}</p>
<p>{{ books|length }}</p>
<p>{{ books|first|length }}</p>
替換將old替換爲new的字符串
<p>{{ username|replace("hellos", "Hello") }}</p>
首寫字母編程大寫
truncate(value,length=255,killwords=False)
截取length長度的字符串。但是必須大於三
<p>{{ username|truncate(length=5) }}</p>
刪除字符串中所有的HTML標籤,如果出現多個空格,將替換成一個空格。
<p>{{ es|striptags }}</p>
es 是一個js代碼,這裏作用是去掉標籤
截取字符串前面和後面的空白字符。
- string
將變量轉換成字符串。
- wordcount
計算一個長字符串中單詞的個數。以空格爲分割標準
三、自定義過濾器
@app.template_filter("handle_time")
def handle_time(time):
"""
小於1分鐘=> 剛剛
大於1分鐘小於1小時=>xx分鐘之前
大於1小時小於24小時=>xxx小時之前
"""
if isinstance(time, datetime):
now = datetime.now() # 獲取現在的時間
# total_seconds 得到總秒數
timestamp = (now - time).total_seconds()
if timestamp < 60:
return "剛剛"
elif timestamp >=60 and timestamp <= 60*60:
return "%s分鐘之前" % int(timestamp/60)
elif timestamp>= 60*60 and timestamp <= 60*60*24:
return "%s小時之前" % int(timestamp/(60*60))
else:
return time
<p>文章發表時間:{{ now_time|handle_time }}</p>