Jinja2 - split macros into multiple files

Given the large number of Jinja2 macros in the file, call macros.html .

I would like to split this file into several smaller files, but it also looks the same when I call it with import .

So, for example, suppose I have

macros.html

 {% 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 %} 

Elsewhere, I import it with import "macros.html" as macros .

I would like to split macros.html into several files, for example A.html and B.html in this example, for example:

A.html

 {% macro A_1() %} A_1 {% endmacro %} {% macro A_2() %} A_2 {% endmacro %} {% macro A_3() %} A_3 {% endmacro %} 

B.html

 {% macro B_1() %} B_1 {% endmacro %} {% macro B_1() %} B_1 {% endmacro %} 

However, I would like the files that used macros.html to still be able to include it with import "macros.html" as macros .

I tried a few things, but they did not work as expected. I usually get the jinja2.environment.TemplateModule object has no attribute 'A_1' error when doing any of the following in macros.html

 {% include "A.html" %} {# or #} {% from "A.html" import A_1 %} 

The only option that seems to work several:

 {% import "A.html" as XYZ %} {% set A_1 = XYZ.A_1 %} 

Unfortunately, in this case, macros in A.html cannot access global macros from the main file, which is different from the behavior when macros were included all in macros.html .

In any case, there is a lot of unnecessary repetition, though, since I would effectively import anonymous module names for each file imported for access only and manually calling each of its macro members.

There seems to be a better option.

One of them, which I reviewed, writes my own file downloader, which downloads and combines glob macros. This is basically a preprocessor that creates "macros.html" from scratch.

+4
source share
1 answer

You can use extends to inherit existing macro files. If in "A" you inherit "B", then import "A" into the page, you can call the macros B as if they were part of the file "A" without additional imports on your page. At your request, it will be displayed as the same file. Here's how to do it:

 {% extends 'macrosdir/file.html' %} 
+4
source

Source: https://habr.com/ru/post/1468996/


All Articles