简体   繁体   中英

Change flash message duration in Flask with Jinja2 templates

In Flask, you can use flash("text", "category") to display a short message that will display for a few seconds on a HTML page. It is rendered by Jinja.

Examples:

flash("Login successful", "success") will display a green message,

flash("Invalid password", "warning") will display a yellow message,

flash("Database destroyed", "error") will display a red message.

Each message will show up for a few seconds and disappear.

I would like to display a success flash message for a longer duration, and maybe change the color. However, I really do not understand where I can change he duration of the message. Is it in the stylesheets used by Jinja?

Many thanks

Flash messages are stored in the SESSION, which by default uses a cookie to track the information.

Message flashing can last the entire period of a request. For instance, if you click on a link with @login_required , the flash message will remain until you make another request.

{% with messages = get_flashed_messages() %}
  {% if messages %}
    {% for message in messages %}
        <div class="alert alert-warning" role="alert">
             {{message}}
        </div>
    {% endfor %}
  {% endif %}
{% endwith %}

You can optionally get rid of the flash message with this:

{% with messages = get_flashed_messages() %}
  {% if messages %}
    {% for message in messages %}
        <div class="alert alert-warning alert-dismissible fade show" role="alert">
              {{message}}
              <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
              </button>
        </div>
    {% endfor %}
  {% endif %}
{% endwith %}

All this is done in flask templates.

Check bootstrap alerts for styling. Otherwise, you can pass custom styles to a flash message through css.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM