Skip to content
Myr

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

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Steven Osborn · committed by Ron DuPlain · parent 676b3a4 · Browse files · 2 files+30 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+30 added−1 removed

  • other:+30 added−1 removed

2 files+30 added−1 removed

modified:docs/patterns/flashing.rst+23 added
115 unmodified lines
116117This is just one example of how to render these flashed messages. One118might also use the category to add a prefix such as119``<strong>Error:</strong>`` to the message.120121Filtering Flash Messages122------------------------123124.. versionadded:: 0.9125126Optionally you can pass a list of categories which filters the results of127:func:`~flask.get_flashed_messages`. This is useful if you wish to128render each category in a separate block.129130.. sourcecode:: html+jinja131132{% with errors = get_flashed_messages(category_filter=["error"]) %}133 {% if errors %}134 <div class="errors">135 <ul>136 {% for message in messages %}137 <li class="error">{{ message }}</li>138 {% endfor %}139 </ul>140 </div>141 {% endif %}142{% endwith %}
modified:flask/helpers.py+7 added-1 removed
262 unmodified lines
263 """264 session.setdefault('_flashes', []).append((category, message))265266267def get_flashed_messages(with_categories=False):267def get_flashed_messages(with_categories=False, category_filter=[]):268 """Pulls all flashed messages from the session and returns them.269 Further calls in the same request to the function will return270 the same messages. By default just the messages are returned,271 but when `with_categories` is set to `True`, the return value will
9 unmodified lines
281282 .. versionchanged:: 0.3283 `with_categories` parameter added.284285 .. versionchanged: 0.9286 `category_filter` parameter added.287288 :param with_categories: set to `True` to also receive categories.289 :param category_filter: whitelist of categories to limit return values290 """291 flashes = _request_ctx_stack.top.flashes292 if flashes is None:293 _request_ctx_stack.top.flashes = flashes = session.pop('_flashes') \294 if '_flashes' in session else []295 if category_filter:296 flashes = filter(lambda f: f[0] in category_filter, flashes)297 if not with_categories:298 return [x[1] for x in flashes]299 return flashes300
384 unmodified lines