1.模板
在前面的示例中,視圖函數的主要作用是生成請求的響應,這是最簡單的請求。實際上,視圖函數有兩個作用:處理業務邏輯和返回響應內容。在大型應用中,把業務邏輯和表現內容放在一起,會增加代碼的復雜度和維護成本。本節學到的模板,它的作用即是承擔視圖函數的另一個作用,即返回響應內容。 模板其實是一個包含響應文本的文件,其中用占位符(變量)表示動態部分,告訴模板引擎其具體值需要從使用的數據中獲取。使用真實值替換變量,再返回最終得到的字符串,這個過程稱為“渲染”。Flask使用Jinja2這個模板引擎來渲染模板。Jinja2能識別所有類型的變量,包括{}。 Jinja2模板引擎,Flask提供的render_template函數封裝了該模板引擎,render_template函數的第一個參數是模板的文件名,后面的參數都是鍵值對,表示模板中變量對應的真實值。
Jinja2官方文檔(http://docs.jinkan.org/docs/jinja2/)
我們先來認識下模板的基本語法:
{% if user %}{{ user }}
{% else %}hello!
<ul>{% for index in indexs %}<li> {{ index }} </li>{% endfor %}
</ul>
通過修改一下前面的示例,來學習下模板的簡單使用:
@app.route('/')
def hello_itcast():return render_template('index.html')@app.route('/user/<name>')
def hello_user(name):return render_template('index.html',name=name)
變量
在模板中{{ variable }}結構表示變量,是一種特殊的占位符,告訴模板引擎這個位置的值,從渲染模板時使用的數據中獲取;Jinja2除了能識別基本類型的變量,還能識別{};
<p>{{mydict['key']}}</p><p>{{mylist[1]}}</p><p>{{mylist[myvariable]}}</p>
from flask import Flask,render_template
app = Flask(__name__)@app.route('/')
def index():mydict = {'key':'silence is gold'}mylist = ['Speech', 'is','silver']myintvar = 0return render_template('vars.html',mydict=mydict,mylist=mylist,myintvar=myintvar)
if __name__ == '__main__':app.run(debug=True)
反向路由:
Flask提供了url_for()輔助函數,可以使用程序URL映射中保存的信息生成URL;url_for()接收視圖函數名作為參數,返回對應的URL;
如調用url_for('index',_external=True)返回的是絕對地址,在下面這個示例中是http://127.0.0.1:5000/index。
@app.route('/index')
def index():return render_template('index.html')@app.route('/user/')
def redirect():return url_for('index',_external=True)
自定義錯誤頁面:
from flask import Flask,render_template@app.errorhandler(404)
def page_not_found(e):return render_template('404.html'), 404
?
2 過濾器:
過濾器的本質就是函數。有時候我們不僅僅只是需要輸出變量的值,我們還需要修改變量的顯示,甚至格式化、運算等等,這就用到了過濾器。 過濾器的使用方式為:變量名 | 過濾器。 過濾器名寫在變量名后面,中間用 | 分隔。如:{{variable | capitalize}},這個過濾器的作用:把變量variable的值的首字母轉換為大寫,其他字母轉換為小寫。 其他常用過濾器如下:
字符串操作:
safe:禁用轉義;
<p>{{ '<em>hello</em>' | safe }}</p>
capitalize:把變量值的首字母轉成大寫,其余字母轉小寫;
<p>{{ 'hello' | capitalize }}</p>
lower:把值轉成小寫;
<p>{{ 'HELLO' | lower }}</p>
upper:把值轉成大寫;
<p>{{ 'hello' | upper }}</p>
title:把值中的每個單詞的首字母都轉成大寫;
<p>{{ 'hello' | title }}</p>
trim:把值的首尾空格去掉;
<p>{{ ' hello world ' | trim }}</p>
reverse:字符串反轉;
<p>{{ 'olleh' | reverse }}</p>
format:格式化輸出;
<p>{{ '%s is %d' | format('name',17) }}</p>
striptags:渲染之前把值中所有的HTML標簽都刪掉;
<p>{{ '<em>hello</em>' | striptags }}</p>
列表操作
first:取第一個元素
<p>{{ [1,2,3,4,5,6] | first }}</p>
last:取最后一個元素
<p>{{ [1,2,3,4,5,6] | last }}</p>
length:獲取列表長度
<p>{{ [1,2,3,4,5,6] | length }}</p>
sum:列表求和
<p>{{ [1,2,3,4,5,6] | sum }}</p>
sort:列表排序
<p>{{ [6,2,3,1,5,4] | sort }}</p>
語句塊過濾(不常用):
{% filter upper %}this is a Flask Jinja2 introduction{% endfilter %}
自定義過濾器:
過濾器的本質是函數。當模板內置的過濾器不能滿足需求,可以自定義過濾器。自定義過濾器有兩種實現方式:一種是通過Flask應用對象的add_template_filter方法。還可以通過裝飾器來實現自定義過濾器。
自定義的過濾器名稱如果和內置的過濾器重名,會覆蓋內置的過濾器。
實現方式一:通過調用應用程序實例的add_template_filter方法實現自定義過濾器。該方法第一個參數是函數名,第二個參數是自定義的過濾器名稱。
def filter_double_sort(ls):return ls[::2]
app.add_template_filter(filter_double_sort,'double_2')
實現方式二:用裝飾器來實現自定義過濾器。裝飾器傳入的參數是自定義的過濾器名稱。
@app.template_filter('db3')
def filter_double_sort(ls):return ls[::-3]
?