0
0
FlaskHow-ToBeginner · 3 min read

How to Use Macros in Jinja2 Templates with Flask

In Flask, you use macros in Jinja2 templates to define reusable blocks of template code with {% macro %}. You can call these macros inside your templates to avoid repeating HTML or logic, making your templates cleaner and easier to maintain.
📐

Syntax

A macro in Jinja2 is defined using the {% macro name(params) %} tag and closed with {% endmacro %}. Inside the macro, you write template code that can use the parameters. You call the macro by its name with arguments like a function.

  • {% macro %}: starts macro definition
  • name(params): macro name and optional parameters
  • {% endmacro %}: ends macro definition
  • Calling macro: use {{ name(args) }} to insert macro output
jinja
{% macro input_field(name, value='', type='text') %}
  <input type="{{ type }}" name="{{ name }}" value="{{ value }}">
{% endmacro %}

<p>Use macro:</p>
{{ input_field('username') }}
💻

Example

This example shows how to define a macro for an input field and use it in a Flask Jinja2 template to generate form inputs dynamically.

python
from flask import Flask, render_template_string

app = Flask(__name__)

@app.route('/')
def index():
    template = '''
    {% macro input_field(name, value='', type='text') %}
      <input type="{{ type }}" name="{{ name }}" value="{{ value }}">
    {% endmacro %}

    <form method="post">
      <label>Username:</label>
      {{ input_field('username') }}<br>
      <label>Password:</label>
      {{ input_field('password', type='password') }}<br>
      <button type="submit">Submit</button>
    </form>
    '''
    return render_template_string(template)

if __name__ == '__main__':
    app.run(debug=True)
Output
<form method="post"> <label>Username:</label> <input type="text" name="username" value=""><br> <label>Password:</label> <input type="password" name="password" value=""><br> <button type="submit">Submit</button> </form>
⚠️

Common Pitfalls

  • Defining macros inside blocks that are not accessible where you want to use them causes errors.
  • For reusing macros across multiple templates, you must put them in a separate file and import them with {% import 'macros.html' as macros %}.
  • Calling macros without parentheses or with wrong parameters leads to template errors.
jinja
{# Wrong: macro defined inside a block and called outside #}
{% block content %}
  {% macro greet(name) %}Hello, {{ name }}!{% endmacro %}
{% endblock %}

{{ greet('Alice') }} {# Error: greet not found here #}

{# Right: define macro in separate file or outside blocks #}

{# macros.html #}
{% macro greet(name) %}Hello, {{ name }}!{% endmacro %}

{# main template #}
{% import 'macros.html' as macros %}
{{ macros.greet('Alice') }}
📊

Quick Reference

Use this quick guide to remember how to define and use macros in Jinja2 with Flask:

ActionSyntax Example
Define macro{% macro name(params) %}...{% endmacro %}
Call macro{{ name(args) }}
Import macros from file{% import 'file.html' as alias %}
Call imported macro{{ alias.name(args) }}

Key Takeaways

Define reusable template code with {% macro %} and call it like a function in Jinja2.
Place macros in separate files and import them for reuse across multiple templates.
Always call macros with parentheses and correct parameters to avoid errors.
Macros help keep your Flask templates clean and DRY by avoiding repeated code.
Remember macros must be defined in accessible scope or imported before use.