Examples

Jinja Macro Template

Using a Macro Template

Jinja macro template defines reusable HTML with {% macro %}.

Introduction to Jinja Macros

Jinja macros are a powerful feature that allows you to define reusable HTML snippets. This is particularly useful in web applications where you have repetitive HTML code. By using the {% macro %} tag, you can create components that can be reused across your templates, improving maintainability and readability.

Defining a Jinja Macro

To define a macro in Jinja, use the {% macro %} block. A macro can accept parameters, making it flexible and dynamic. Here's a simple example of a macro that creates a button:

Using a Jinja Macro

Once a macro is defined, it can be used in your templates by calling it with the appropriate parameters. Here’s how you can use the button macro we defined:

Organizing Macros

For better organization, it's common to store macros in separate files and import them into your templates. This keeps your template files clean and manageable. You can import macros using the {% import %} statement as shown in the previous example.

Advanced Macro Usage

Jinja macros can also include logic, such as loops and conditionals, to create more complex components. Here’s an example of a macro that generates a list:

This macro can be used to render a list of items dynamically:

Conclusion

Jinja macros are a versatile tool for creating reusable components in your web templates. By defining macros, you can simplify your code and make it easier to maintain. They can handle both simple and complex HTML generation, allowing you to write DRY (Don't Repeat Yourself) code efficiently.