from flask import Flask, render_template
app = Flask(__name__)
"""模板使用"""
@app.route("/index")
def index():
data = {
"age": 18,
"city_dict": {"city1":"putian", "city2":"fuzhou"},
"num_list": [1, 2, 3, 4, 5]
}
# render_template接收的参数是模板文件、后面是关键字参数
return render_template("index.html", name="zhangsan", **data)
"""过滤器"""
# 自定义过滤器
def list_step_2(li):
return li[::2]
# 注册过滤器
app.add_template_filter(list_step_2, "l2")
#自定义过滤器
@app.template_filter("l3")
def list_step_3(li):
return li[::3]
if __name__ == '__main__':
app.run(debug=True)
页面代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>{{name}}</p>
<p>{{age}}</p>
<p>{{city_dict["city1"]}}</p>
<p>{{city_dict.city1}}</p>
<p>{{num_list[0]}}</p>
<p>{{num_list[0]+num_list[1]+num_list[2]}}</p>
<hr>
<p>{{num_list|l2}}</p>
<p>{{num_list|l3}}</p>
</body>
</html>