flash消息显示

  1. 说明:

    当用户发出请求后,有时状态发生了改变,需要给与提示、警告等信息时,通过可以弹出警告框,然后用户可以手动取消掉。

  2. 使用:bootstrap显示,可以叉掉消息

    在合适的时候书写flash消息,使用flash函数

    
    @app.route('/', methods=['GET', 'POST'])
    def index():
        # 创建表单对象
        form = NameForm()
        # 表单校验
        if form.validate_on_submit():
            last_name = session.get('name')
            # 原来有,并且与现在的不一样,给出提示消息
            if last_name and last_name != form.name.data:
                flash('大哥,又换签名')
            session['name'] = form.name.data
            return redirect(url_for('index'))
        name = session.get('name')
        # 渲染时分配到模板文件
        return render_template('form.html', form=form, name=name)

    在模板文件中,通过get_flashed_messages函数获取所有的flash消息,如下:

    {% extends 'bootstrap/base.html' %}
    
    {% block title %}
        flash消息闪现
    {% endblock %}
    
    {% block content %}
        <div class="container">
            <div class="row">
                {% for message in get_flashed_messages() %}
                    <div class="alert alert-warning alert-dismissible" role="alert">
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                        {{ message }}
                    </div>
                {% endfor %}
            </div>
        </div>
    {% endblock %}
  3. 建议:若整个的项目多处使用flash消息,可以将flash消息的显示放在基模板中

猜你喜欢

转载自blog.csdn.net/pzl_pzl/article/details/80861182