@TOC
返回正常html网页1.在templates目录下新建about.html网页
2.编写对应的视图函数,引入新的方法render_template,用来返回html格式的页面
@app.route('/about')
def about():
context = {
'username': '张三'
}
return render_template('about.html', **context)
3.在html中标记对应的名字的位置 {{ username}} ,模板语言的标记方法,
Title
这里是名字{{ username }}
成果展示
jinja2模板过滤器
通过语法过滤数据有几个字符
这里是名字{{ username|length }}
join过滤器,将列表中的多个元素,变成字符串类型
{{ books|join('//') }}
# 这样展示的就是 一整个字符串
控制语句,分为if语句和for语句
@app.route('/control/')
def control(age):
# 接收前端传入的年龄
context = {
"age": age,
'books': ['1', 2, 3, 4, 5]
}
return render_template('control.html', **context)
# 前端页面中进行判断,根据age的大小进行不同的展示,注意要点是要有结束的endif
{% if age > 18 %}
你已经成年
{% elif age < 18 %}
你没有成年
{% elif age == 18 %}
你刚好成年
{% endif %}
for语句
@app.route('/control/')
def control(age):
# 接收前端传入的年龄
context = {
"age": age,
'books': ['1', 2, 3, 4, 5]
}
return render_template('control.html', **context)
# 根据后端传过来的列表数据,进行循环,然后展示
-
{% for i in books %}
- {{ i }} {% endfor %}
成果
当需要循环的参数为字典类型时
def control(age):
context = {
"age": age,
'books': ['1', 2, 3, 4, 5],
'person': {'name': 'lll', 'age': 18}
}
return render_template('control.html', **context)
-
{% for l1, l2 in person.items() %}
{{ l1 }}:{{ l2 }}
{% endfor %}


![flask浅学(3)[模板渲染] flask浅学(3)[模板渲染]](http://www.mshxw.com/aiimages/31/753381.png)
