Sling Academy
Home/FastAPI/How to create and use macros in Jinja

How to create and use macros in Jinja

Last updated: November 28, 2024

Jinja is a modern and designer-friendly templating engine for Python that allows developers to quickly generate HTML with dynamic content. One powerful feature of Jinja is the ability to use macros, which are essentially reusable snippets of template code. In this article, we'll explore how to create and utilize Jinja macros in your projects.

Creating a Macro in Jinja

Creating a macro in Jinja is straightforward. A macro is similar to a function in Python: it has a name, can accept parameters, and can return a value. To define a macro in Jinja, you use the {% macro %} syntax.

{% macro input_field(name, value='', type='text') %}
    <input type="{{ type }}" name="{{ name }}" value="{{ value }}"/>
{% endmacro %}

In the example above, we've created a macro named input_field. This macro generates an HTML input element, allowing you to specify its type, name, and value. The parameters have default values, making them optional when the macro is used.

Using a Macro

Once a macro has been defined, you can use it elsewhere in your template. Simply call the macro by its name and provide any necessary arguments.

<form>
    {{ input_field('username') }}
    {{ input_field('password', type='password') }}
    <button type="submit">Submit</button>
</form>

In this example, we call the input_field macro twice to generate input fields for a form. The first call creates a text input for a username, and the second call creates a password input field. By using macros, you keep your templates DRY (Don't Repeat Yourself) and make them easier to maintain.

Passing a Sequence to a Macro

Jinja macros can also handle complex data types such as lists or dictionaries, allowing you to keep your templates even more dynamic and flexible.

{% macro user_info(user) %}
    <div class="user">
        <p>Name: {{ user.name }}</p>
        <p>Email: {{ user.email }}</p>
    </div>
{% endmacro %}

You can use this macro by passing a dictionary that contains the user's data:

{% set user = {'name': 'Jane Doe', 'email': '[email protected]'} %}
{{ user_info(user) }}

This renders a div containing the user's name and email address.

Conclusion

Macros in Jinja provide a powerful way to create reusable, maintainable, and efficient templates. By understanding how to define and use macros, you can build templates that are cleaner and faster to develop. Experiment with different types of macros in your existing projects to fully harness the potential of Jinja!

Next Article: How to decode Jinja response to string

Previous Article: Reuse templates with Include and Extend in Jinja

Series: Jinja Templates

FastAPI

You May Also Like

  • Popular useful built-in Jinja filters you should know
  • How to remove consecutive whitespace in rendered Jinja pages
  • How to format large numbers with thousand separators in Jinja template
  • How to format date time in Jinja templates
  • FastAPI + Jinja: How to create custom filters
  • How to pass variables from Python (FastAPI) to Jinja
  • How to decode Jinja response to string
  • How to use namespace in Jinja
  • How to use if/ else in Jinja
  • How to use loops in Jinja
  • FastAPI + SQLAlchemy: Using cursor-based pagination
  • FastAPI: How to use macros in Jinja templates
  • Fixing Common Swagger UI Errors in FastAPI
  • FastAPI Error: 307 Temporary Redirect – Causes and Solutions
  • FastAPI Error: Expected UploadFile, received ‘str’
  • Resolving FastAPI ImportError: No Known Parent Package
  • FastAPI Error: No module named ‘pydantic_core._pydantic_core’
  • Resolving FastAPI 422 Error: Value is not a valid dict
  • Resolving the FastAPI Circular References Error