Skip to content

Creating macros

How to create new Jinja2 macros that follow the bluefox-components conventions.

Conventions

  1. Explicit parameters for the 90% case
  2. attrs dict for arbitrary HTML attributes (HTMX, data-*, aria-*)
  3. Pico-native HTML — emit semantic elements Pico already styles
  4. {% call %} convention for content slots
  5. No JavaScript by default

Example: a badge macro

{# bfx/badge.html #}

{% macro badge(label, variant="default", attrs={}) %}
<span class="badge badge-{{ variant }}"
  {% for key, val in attrs.items() %}{{ key }}="{{ val }}"{% endfor %}
>{{ label }}</span>
{% endmacro %}

Usage:

{% from "bfx/badge.html" import badge %}

{{ badge("New") }}
{{ badge("Archived", variant="secondary") }}

Content slots with {% call %}

For components wrapping arbitrary content:

{# bfx/card.html #}

{% macro card(title=none, footer=none, attrs={}) %}
<article {% for key, val in attrs.items() %}{{ key }}="{{ val }}"{% endfor %}>
  {% if title %}<header>{{ title }}</header>{% endif %}
  {{ caller() }}
  {% if footer %}<footer>{{ footer }}</footer>{% endif %}
</article>
{% endmacro %}

Usage:

{% call card(title="Users") %}
  <p>42 active users</p>
{% endcall %}