title: Jinja2 - break macros out across multiple files
body: <p>Given a lengthy number of Jinja2 macros in a file, let's call it <code>macros.html</code>.</p>
  
  <p>I would like to break that file up into a number of smaller files, but have it appear the same outwardly when I call it with an <code>import</code>.</p>
  
  <p>So for example, suppose I have </p>
  
  <h3>macros.html</h3>
  
  <pre><code>{% macro A_1() %} A_1 {% endmacro %}
  {% macro A_2() %} A_2 {% endmacro %}
  {% macro A_3() %} A_3 {% endmacro %}
  
  {% macro B_1() %} B_1 {% endmacro %}
  {% macro B_1() %} B_1 {% endmacro %}
  </code></pre>
  
  <p>Elsewhere I import this with <code>import "macros.html" as macros</code>.</p>
  
  <p>I would like to break <code>macros.html</code> down into multiple files, such as <code>A.html</code> and <code>B.html</code> in this example, like this: </p>
  
  <h3>A.html</h3>
  
  <pre><code>{% macro A_1() %} A_1 {% endmacro %}
  {% macro A_2() %} A_2 {% endmacro %}
  {% macro A_3() %} A_3 {% endmacro %}
  </code></pre>
  
  <h3>B.html</h3>
  
  <pre><code>{% macro B_1() %} B_1 {% endmacro %}
  {% macro B_1() %} B_1 {% endmacro %}
  </code></pre>
  
  <p>However I would like the files that used <code>macros.html</code> to be able to still include it with the <code>import "macros.html" as macros</code>.</p>
  
  <p>I have tried a number of things, but they have not worked as expected. I typically get an error of <code>jinja2.environment.TemplateModule object has no attribute 'A_1'</code> when doing any of the following in <code>macros.html</code></p>
  
  <pre><code>{% include "A.html" %}
  
  {# or #}
  
  {% from "A.html" import A_1 %}
  </code></pre>
  
  <p>The only option that seems to somewhat work is:</p>
  
  <pre><code>{% import "A.html" as XYZ %}
  {% set A_1 = XYZ.A_1 %}
  </code></pre>
  
  <p>Unfortunately in this case the macros in <code>A.html</code> cannot access global macros from the main file, which differs from the behaviour when the macros were included all in <code>macros.html</code>.</p>
  
  <p>In any case there is a lot of unnecessary repetition going on there, though, since I would be effectively importing anonymous module names for each file imported just to access and manually name each of its macro members.</p>
  
  <p>It seems like there should be a better option.</p>
  
  <p>One I have considered is writing my own file loader that loads and concatenates the glob of macros. Basically a pre-processor that creates "macros.html" from scratch.</p>