概述
Flask框架使用的模板引擎是 Jinja2
Jinja2 是一个现代的,设计者友好的,仿照 Django 模板的 Python 模板语言。
官方文档:http://jinja.pocoo.org/
中文文档:http://docs.jinkan.org/docs/jinja2/
特点
速度快,够有效的将 业务逻辑 和 页面逻辑 分开,使代码可读性增强、并且更加容易理解和维护
为什么要使用模板
比如上面的淘宝网页,样式是固定的,但内容是动态变化的,不论搜索什么商品,都是这个界面,像这种情况就适合使用模板
感性认识
模板文件夹
在工程目录下,创建 templates 目录,该目录就是默认的 flask模板目录,模板文件都放在这个目录下。
提示:下面有修改默认目录的方法
模板文件
在 templates 目录下,新建 index.html 文件,内容如下
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
您好,{{username}}
</body>
</html>
保存到 templates文件夹
python代码
# coding=utf-8
from flask import Flask,render_template
app=Flask(__name__)
@app.route('/')
def index():
return render_template('index.html',username='李雷')
if __name__ == "__main__":
app.run(debug=True)
要使用 render_template() 函数
render_template()函数
该函数是 渲染模板 (将数据显示到页面上),定义如下:
render_template(template_name_or_list, **context)
参数:
template_name_or_list:模板文件名
默认情况下,模板文件必须放在
templates文件夹**context:关键字参数,传递给模板的数据
传递多个数据
模板代码
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
您好,{{username}},年龄:{{age}},所在学校:{{school}}
</body>
</html>
python代码方式一:指定参数名
# coding=utf-8
from flask import Flask,render_template
app=Flask(__name__)
@app.route('/')
def index():
return render_template('index.html',username='李雷',age=20,school='清华')
if __name__ == "__main__":
app.run(debug=True)
python代码方式二:传递dict类型数据
对于关键字参数,还可以传dict类型,但要做特殊处理
# coding=utf-8
from flask import Flask,render_template
app=Flask(__name__)
@app.route('/')
def index():
data={
'username':'李雷',
'age':20,
'school':'清华'
}
return render_template('index.html',**data)
if __name__ == "__main__":
app.run(debug=True)
遍历list类型数据
视图函数向模板传递list类型数据,模板循环显示list里面的元素
python代码:
# coding=utf-8
from flask import Flask,render_template
app=Flask(__name__)
@app.route('/')
def index():
return render_template('list.html',phones=['华为','小米','诺基亚','oppo','vivo'])
if __name__ == "__main__":
app.run(debug=True)
模板代码:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<ul>
{% for item in phones%}
<li>{{item}}</li>
{%endfor%}
</ul>
</body>
</html>
模板中的if语句
修改上面的模板,在循环显示品牌时,如果是诺基亚就不显示
模板代码:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<ul>
{% for item in phones%}
{%if item!='诺基亚'%}
<li>{{item}}</li>
{%endif%}
{%endfor%}
</ul>
</body>
</html>
模板遍历 dict类型数据
视图函数向模板传递dict类型数据,模板循环显示dict里面的key和value
python代码:
# coding=utf-8
from flask import Flask,render_template
app=Flask(__name__)
@app.route('/testdict')
def testdict():
return render_template('dict.html',data={'商品名称':'小米9','内存':'8G','电池':'4000毫安'})
if __name__ == "__main__":
app.run(debug=True)
模板代码:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<ul>
{% for key,value in data.items()%}
<li>{{key}}:{{value}}</li>
{%endfor%}
</ul>
</body>
</html>
修改模板文件夹
模板的文件夹,默认为 templates 文件夹。创建 flask 对象时,通过 template_folder 参数可以修改该目录
提示 一般不用修改
app = Flask(__name__,template_folder='abc')
