Allow category filtering in get_flashed_messages to allow rending categories in separate html blocks

This commit is contained in:
Steven Osborn 2011-10-16 19:44:37 -07:00 committed by Ron DuPlain
parent 676b3a4c13
commit fa069f94de
2 changed files with 30 additions and 1 deletions

View File

@ -117,3 +117,26 @@ categories. The loop looks slightly different in that situation then:
This is just one example of how to render these flashed messages. One
might also use the category to add a prefix such as
``<strong>Error:</strong>`` to the message.
Filtering Flash Messages
------------------------
.. versionadded:: 0.9
Optionally you can pass a list of categories which filters the results of
:func:`~flask.get_flashed_messages`. This is useful if you wish to
render each category in a separate block.
.. sourcecode:: html+jinja
{% with errors = get_flashed_messages(category_filter=["error"]) %}
{% if errors %}
<div class="errors">
<ul>
{% for message in messages %}
<li class="error">{{ message }}</li>
{% endfor %}
</ul>
</div>
{% endif %}
{% endwith %}

View File

@ -264,7 +264,7 @@ def flash(message, category='message'):
session.setdefault('_flashes', []).append((category, message))
def get_flashed_messages(with_categories=False):
def get_flashed_messages(with_categories=False, category_filter=[]):
"""Pulls all flashed messages from the session and returns them.
Further calls in the same request to the function will return
the same messages. By default just the messages are returned,
@ -282,12 +282,18 @@ def get_flashed_messages(with_categories=False):
.. versionchanged:: 0.3
`with_categories` parameter added.
.. versionchanged: 0.9
`category_filter` parameter added.
:param with_categories: set to `True` to also receive categories.
:param category_filter: whitelist of categories to limit return values
"""
flashes = _request_ctx_stack.top.flashes
if flashes is None:
_request_ctx_stack.top.flashes = flashes = session.pop('_flashes') \
if '_flashes' in session else []
if category_filter:
flashes = filter(lambda f: f[0] in category_filter, flashes)
if not with_categories:
return [x[1] for x in flashes]
return flashes