Flask提供了一个很方便的flash函数,在视图函数里只需要一行就可以在网页上闪现一个消息(alert),像这样:
1 |
flash(u'登录成功,欢迎回来!') |
我们今天来为它添加样式。
基本用法
在视图函数里使用flash:
1 |
flash(u'要闪现的消息内容') |
然后在基模板里使用get_flashed_messages()
来获取消息,并渲染出来。
比如《Flask Web开发》里使用alert-warning渲染所有的消息:
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 %} |
下面我们使用Bootsrtap的消息样式来渲染不同的消息。
使用Bootstrap的消息(alert)样式
如果想要开启消息的分类,需要在调用get_flashed_messages()
时传入参数with_categories=True
。这时,在基模板里使用这个函数获取消息时,得到的是一个由(category, message)
形式的元组组成的一个列表。
之后,就可以在使用flash函数时加入消息类别:
1 |
flash(u'登录成功,欢迎回来!', 'info') |
你可以使用‘success’、‘info’、‘warning’、‘danger’这四个值中的任一个。具体样式文章开头的图片。
这时基模板里渲染消息的部分要改成这样:
1 2 3 4 5 6 |
{% for message in get_flashed_messages(with_categories=True) %} <div class="alert alert-{{ message[0] }}"> <button type="button" class="close" data-dismiss="alert">×</button> {{ message[1] }} </div> {% endfor %} |
这样一来,每个消息就会按照我们提供的分类样式来渲染了。
DIY
当然,你也可以自己定义每一类消息的样式。我推荐你在Bootstrap的四个类别的基础上增加样式,这样只需要在你的css文件里添加一个新的alert样式,比如下面我添加了一个code样式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
/* code alert style, by Grey Li*/ .alert-code { color: #66ff66; background-color: #000000; border-color: #ebccd1; } .alert-code hr { border-top-color: #000066; } .alert-code .alert-link { color: #ff9900; } |
然后使用:
1 |
flash(u'要闪现的消息', 'code') |
效果:
如果你不用Bootstrap,只需要加将上面的为div指定类的那行改成:
1 |
<div class="{{ message[0] }}"> |
然后在你的css文件里定义类别对应的样式就可以了。
多看源码
源码里面有很多有趣和有价值的东西,要养成看源码的习惯。很多问题靠看源码里的注释基本上就能解决。所以,问题的正确解决方式应该是:看源码——Google——提问。
- flash()和get_flashed_messages()的源码:https://github.com/pallets/flask/blob/master/flask/helpers.py(从第363行开始)
- flask文档(Message Flashing):http://flask.pocoo.org/docs/0.11/patterns/flashing/
- Bootstrap文档(A):Alerts · Bootstrap。