渲染模版(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>