Get It Done! Part 8: Flash Messages
Notes
In this video lesson we learn to use flash messages to flexibly display messages to users based on their actions. Among other benefits, message flashing allows you to display messages to the user when you are redirecting them (i.e., not rendering a template). To use flash messages, we'll need to:
-
Import the
flashfunction from Flask -
Create a
flashfunction call inmain.py, e.g.,flash("Logged In") -
Access the flash message in your
base.htmlusing jinja2 syntax, including the newly-introduced "with" block:{% with messages = get_flashed_messages() %} <ul> {% for message in messages %} <li>{{message}}</li> {% endfor %} </ul> {% endwith %} -
Add categories to your
flashfunction call so that you can add styling to your flash messages, e.g.flash("Logged In", "success"). You'll also need to modify your base template as follows:{% with messages = get_flashed_messages(with_categories=True) %} <ul> {% for category,message in messages %} <li class="{{category}}">{{message}}</li> {% endfor %} </ul> {% endwith %} - Then add whatever CSS style rules you wish for those categories in a
<style>tag in theheadof the base template.
Code
View the final code for this lesson.