Jinja Macros Introduction
n
Macros in Jinja2 are powerful tools for creating reusable code snippets, much like **functions in regular programming languages**. They are a cornerstone of the “Don’t Repeat Yourself” (DRY) principle, allowing you to define a template element once and reuse it across your project, saving time and ensuring consistency.
nn
Defining and Calling a Macro
n
You define a macro using the {% macro ... %} and {% endmacro %} tags. A macro can take arguments and even provide default values. Once defined, you can call it just like a function in your template.
nn
{# The macro definition #}n{% macro input(name, value='', type='text', size=20) -%}n n{%- endmacro %}nn{# Calling the macro with and without arguments #}
n{{ input(‘username’) }}n
n n
n{{ input(‘password’, type=’password’) }}n
n n
n
nn
Importing Macros from Another Template
n
For better organization, you can define macros in separate files and **import** them when needed. This keeps your main template code clean and allows you to share macros across multiple templates.
nn
{# Import all macros from 'forms.html' into a namespace #}n{% import 'forms.html' as forms %}
n
n
n{# Or, import a specific macro directly #} {% from ‘forms.html’ import input %}n
n
n
n n
n
n
n
