Macro Scope and Template Inheritance
n
Due to how scopes work in Jinja2, a macro defined in a child template does not override a macro with the same name in a parent template. The parent’s macro is always accessible and takes precedence within its scope, which prevents unintended overwrites.
nn
Understanding the Scoping Rules
n
When a child template **extends** a parent template, it effectively inherits all of the parent’s components, including its macros. The parent’s macros are loaded into the template’s scope first, and any similarly named macros in the child template will not overwrite them. This ensures that a parent template’s core components, such as a consistent header or navigation bar, will always function as intended across all child pages.
nn
nn
Code Demonstration
n
The following example demonstrates this behavior. Despite the child template defining its own foo macro, the call to `{{ foo() }}` inside the `body` block will execute the parent’s macro.
nn
`layout.txt` (Parent Template)
n
{% macro foo() %}LAYOUT{% endmacro %}n{% block body %}{% endblock %}
n
`child.txt` (Child Template)
n
{% extends 'layout.txt' %}n{% macro foo() %}CHILD{% endmacro %}n{% block body %}{{ foo() }}{% endblock %}
n
The final output will be: **LAYOUT**.
nn
n
n
