模板簡介:
模板是一個web開發(fā)必備的模塊。因為我們在渲染一個網(wǎng)頁的時候,并不是只渲染一個純文本字符串,而是需要渲染一個有富文本標簽的頁面。這時候我們就需要使用模板了。在Flask中,配套的模板是Jinja2,Jinja2的作者也是Flask的作者。這個模板非常的強大,并且執(zhí)行效率高。以下對Jinja2做一個簡單介紹!
Flask渲染Jinja模板:
要渲染一個模板,通過render_template方法即可,以下將用一個簡單的例子進行講解:
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/about/')
def about():
return render_template('about.html')
當訪問/about/的時候,about()函數(shù)會在當前目錄下的templates文件夾下尋找about.html模板文件。如果想更改模板文件地址,應(yīng)該在創(chuàng)建app的時候,給Flask傳遞一個關(guān)鍵字參數(shù)template_folder,指定具體的路徑,再看以下例子:
from flask import Flask,render_template
app = Flask(__name__,template_folder=r'C:\templates')
@app.route('/about/')
def about():
return render_template('about.html')
以上例子將會在C盤的templates文件夾中尋找模板文件。還有最后一點是,如果模板文件中有參數(shù)需要傳遞,應(yīng)該怎么傳呢,我們再來看一個例子:
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/about/')
def about():
# return render_template('about.html',user='zhiliao')
return render_template('about.html',**{'user':'zhiliao'})
以上例子介紹了兩種傳遞參數(shù)的方式,因為render_template需要傳遞的是一個關(guān)鍵字參數(shù),所以第一種方式是順其自然的。但是當你的模板中要傳遞的參數(shù)過多的時候,把所有參數(shù)放在一個函數(shù)中顯然不是一個好的選擇,因此我們使用字典進行包裝,并且加兩個*號,來轉(zhuǎn)換成關(guān)鍵字參數(shù)。
如果想深入學習Flask,可以觀看這套免費Flask教學視頻:Flask入門到項目實戰(zhàn)
</article>
版權(quán)聲明: https://blog.csdn.net/huangyong1314/article/details/74648640