3

I have a master template that imports global macros. Another template extends the master template for a section of the site. The section template imports section-global macros with context. In the section-global macros, a global macro is accessed via its imported name.

(For simplicity's sake, I've pared down the templates.)

master.html

{% import 'global_macros.html' as m %}
<html>
<body>
{% block body %}{% endblock %}
</body>
</html>

section.html

{% extends 'master.html' %}
{% import 'section_macros.html' as m_section with context %}

global_macros.html

{% macro some_macro() %}
this is a macro!
{% endmacro %}

section_macros.html

{% macro something() %}
{{ m.some_macro() }}
{% endmacro %}

This doesn't work as expected: an UndefinedError is raised and the imported global macro name (m) isn't defined. The global macros work throughout all the children templates; just not in the imported macros.

If I import the global macros directly into the section macros file, it works fine:

section_macros.html

{% import 'global_macros.html' as m %}
{% macro something() %}
{{ m.some_macro() }}
{% endmacro %}

Or if I import the global macros into the section template, it works fine:

section.html

{% extends 'master.html' %}
{% import 'global_macros.html' as m %}
{% import 'section_macros.html' as m_section with context %}

Based on my understanding on Jinja and scopes, the m variable should be passed on to the section macros template from the master because I've given it the context it needs and the m variable is available within the section template and its children.

Am I doing something wrong? Or is this a limitation or bug of Jinja?

Logan Bibby
  • 1,167
  • 1
  • 10
  • 31

0 Answers0