Skip to content

Instantly share code, notes, and snippets.

@alexferl
Last active January 1, 2016 17:09
Show Gist options
  • Save alexferl/8175403 to your computer and use it in GitHub Desktop.
Save alexferl/8175403 to your computer and use it in GitHub Desktop.
Jinja2 macro for Twitter Bootstrap 3 alerts.
{% macro render_alert(category=None, dismissable=False, error=False,
message=None, link=None) -%}
{% if not category and not error %}
{% set category = 'success' %}
{% elif error %}
{% set category = 'danger' %}
{% endif %}
<div class="alert alert-{{ category }}
{% if dismissable %} alert-dismissable{% endif %}">
{% if dismissable %}
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
{% endif %}
{% if category == 'success' %}
<strong>Yay!</strong> {{ message|safe }}
{% elif category == 'danger' %}
<strong>Uh-oh!</strong> {{ message|safe }}
{% elif category == 'info' %}
<strong>Heads-up!</strong> {{ message|safe }}
{% elif category == 'warning' %}
<strong>Not so fast!</strong> {{ message|safe }}
{% endif %}
{% if link %}
<a href="{{ link.href }}" class="alert-link">{{ link.message|safe }}</a>
{% endif %}
</div>
{%- endmacro %}
@alexferl
Copy link
Author

Use like this in your templates:

Import first:

{% from "formhelpers.py" import render_alert %}

Dismissable error message:

{{ render_alert(error=True, message='Incorrect login', dismissable=True) }}

Undismissable warning message:

{{ render_alert(category='warning', message='Be careful') }}

With a link:

{{ render_alert(error=True, message='Incorrect login', link={'href': '/forgot', 'message': 'Forgot password?'}) }}

and so on.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment