Flask提供了一个很方便的flash函数,在视图函数里只需要一行就可以在网页上闪现一个消息(alert),像这样:1
flash('Hello Flask')
基本用法
在视图函数里使用flash:1
flash('要闪现的消息内容')
然后在基模板里使用 get_flashed_messages()
来获取消息,并渲染出来。1
2
3
4
5
6{% for message in get_flashed_messages() %}
<div class="alert alert-warning">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ message }}
</div>
{% endfor %}
下面我们使用Bootstrap的消息样式来渲染不同的消息。
使用Bootstrap的消息(alert) 样式
如果想要开启消息的分类,需要在调用 get_flashed_messages()
时传入参数 with_categories=True
.这时,在基模板里使用这个函数获取消息时,得到的是一个由 (category, message)
形式的元组组成的一个列表。
之后,就可以在使用flash函数时加入消息类别:1
flash('登录成功,欢迎回来', 'info')
你可以使用 success、info、warning、danger
这四个值中的任一个。具体样式见下面图片
这时基模板里渲染消息的部分要改成这样:1
2
3
4
5
6{% for message in get_flashed_messages(with_categories=True) %}
<div class="alert clert-{{ message[0] }}">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ message[1] }}
</div>
{% endfor %}
这样一来,每个消息就会按照我们提供的分类样式来渲染。
多看源码
源码里面由很多有趣和有价值的东西,要养成看源码的习惯。很多问题靠看源码里的注释基本上就能解决。所以,问题的正确解决方式应该是:看源码——查文档——Google——提问。
- flash()和get_flashed_messages()的源码:https://github.com/pallets/flask/blob/master/flask/helpers.py
- flask文档(Message Flashing):http://flask.pocoo.org/docs/0.11/patterns/flashing/
- Bootstrap文档(A):Alerts · Bootstrap