Jinja: Introduction to Macros and Imports
n
n
Jinja2 supports putting reusable code into macros, which can be imported from other templates. This is a powerful feature that works similarly to Python’s import statements, allowing you to organize your code and make your templates more modular. A key thing to remember is that imports are cached, and imported templates don’t have access to the current template’s variables by default.
nn
n
Two Ways to Import
n
There are two primary methods for importing templates:
nn
- n
- Import a complete template into a variable: This method gives you access to all public macros and top-level variables from the imported file via the variable.
- Request specific macros or exported variables: This allows you to cherry-pick what you need from the imported template, avoiding a cluttered namespace.
n
n
n
nn
n
Code Demonstration
n
Here are examples of both import methods. First, let’s assume we have a file named `forms.html` with a macro for rendering a text input:
nn
forms.html (the file to be imported)
n
{% macro text_input(label, name, value='') %}n <label>{{ label }}</label>n <input type="text" name="{{ name }}" value="{{ value }}">n{% endmacro %}
n
Method 1: Importing the entire template
n
{% import 'forms.html' as forms %}nn<p>{{ forms.text_input('Username', 'username') }}</p>
n
Method 2: Importing specific macros
n
{% from 'forms.html' import text_input %}nn<p>{{ text_input('Email', 'email') }}</p>
n
Both methods achieve the same result, but the `from … import …` syntax is cleaner if you only need a single macro or variable.
nn
n
n
