0
0
Flaskframework~5 mins

Macros for reusable components in Flask

Choose your learning style9 modes available
Introduction

Macros help you write small reusable pieces of HTML code once and use them many times. This saves time and keeps your templates clean.

When you have a button style used in many places on your website.
When you want to create a common form input that repeats in different pages.
When you need to show a user profile card in multiple templates.
When you want to keep your HTML templates organized and avoid repeating code.
Syntax
Flask
{% macro macro_name(parameters) %}
  <!-- HTML code here -->
{% endmacro %}

{{ macro_name(arguments) }}
Macros are defined inside Jinja2 templates using {% macro %} and {% endmacro %}.
You call a macro by writing {{ macro_name() }} with any needed arguments.
Examples
This macro creates a simple button with the text you provide.
Flask
{% macro button(text) %}
  <button>{{ text }}</button>
{% endmacro %}

{{ button('Click me') }}
This macro creates a colored alert box. You can change the alert type like 'success' or 'error'.
Flask
{% macro alert(message, type='info') %}
  <div class="alert alert-{{ type }}">{{ message }}</div>
{% endmacro %}

{{ alert('Success!', 'success') }}
Sample Program

This example shows how to define a card macro in one template file and import it in another. Then you use the macro to create multiple cards with different content.

Flask
{# templates/macros.html #}
{% macro card(title, content) %}
  <div class="card">
    <h2>{{ title }}</h2>
    <p>{{ content }}</p>
  </div>
{% endmacro %}

{# templates/index.html #}
{% import 'macros.html' as ui %}

<html lang="en">
<head><title>Macro Example</title></head>
<body>
  {{ ui.card('Welcome', 'This is a reusable card component.') }}
  {{ ui.card('Note', 'You can reuse this card anywhere.') }}
</body>
</html>
OutputSuccess
Important Notes

Always import macros with a name to avoid conflicts.

Macros can accept default values for parameters to make them flexible.

Use macros to keep your templates DRY (Don't Repeat Yourself).

Summary

Macros let you write reusable HTML blocks in Flask templates.

Define macros with {% macro %} and call them with {{ macro_name() }}.

Import macros from other templates to organize your code better.