渲染模版(html文件)html
A、模版文件(html)放入到template目錄下,項目啓動的時候會從template目錄裏查找,python
B、從flask中導入「render_tempalte」函數flask
C、在視圖函數中,使用render_template函數,渲染模版(只須要填寫模版名稱便可)app
示例:函數
from flask import Flask,url_for,redirect,render_template #導入模版函數 app = Flask(__name__) @app.route('/') def index(): info = { #定義字典 'username' :'name', 'gender':"man", 'height' : "178" } #若是有多個參數,能夠將全部的參數放到字典中,而後以**kwargs的方式傳遞進去,info爲上面定義的字典 return render_template('index.html',**info) #這裏直接寫模版文件名稱,若是在模版文件在temlate/html目錄下,則這裏須要寫'html/index.html' #渲染模版,傳參數,若是參數較少,能夠直接寫關鍵字參數及值,以下: #return render_template('index.html',username='name',gender="man",height="178") if __name__ == '__main__': app.run(debug=True) if __name__ == '__main__': app.run(debug=True)
index.htmlurl
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>第一個flask頁面</p> <p>姓名:{{ username }}</p> #使用{{}}用來使用變量 <p>height:{{ height }}</p> </body> </html>
模版中的變量說明,示例:spa
flask_one.py
#encoding:utf-8 from flask import Flask,url_for,redirect,render_template app = Flask(__name__) @app.route('/') def index(): class Person(object): name='tttt' age=18 p = Person() info = { 'username' :'name', 'gender':"man", 'height' : "178", 'person':p, 'city':{ 'bj':"bj", 'tj':'tj' } } return render_template('index.html',**info) #return render_template('index.html',username='name',gender="man",height="178") if __name__ == '__main__': app.run(debug=True) index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>第一個flask頁面</p> <p>姓名:{{ username }}</p> <p>height:{{ height }}</p> <hr> <p>{{ person.name }}---{{ person.age }}</p> #此處對應上面py中定義的Person類 <p>{{ city.bj }}</p> #此處對應字典內的字典,一共兩種取值方式,一是常規的字典取值,二是用"." <p>{{ city['tj'] }}</p> </body> </html>