Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I import a nested jinja macro?

I would like to import a nested jinja macro into a rest file and call it.

So we have main.rst file which imports a collection_of_macros.jinja and inside the collection_of_jinja_macros.jinja is a list of imports which are importing jinja macros.

main.rest file has:
{% import 'path/collection_of_jinja_macros.jinja' as macros%}
{{macros.macro1() }}

then the collection_of_jinja_macros.jinja has 
{% include 'path/macro1.jinja' %}
{% include 'path/macro2.jinja' %}

I've tried using include,import, and toctree syntax to pull in the macros but I can never find success.

The rest file cannot never resolve the macro lookup.

like image 739
Matt Avatar asked Mar 16 '26 21:03

Matt


1 Answers

I had the exact same question and found a way that works. The trick is that your collection_of_jinja_macros.jinja needs to not only import the macros, but also needs to export those collections of macros with a variable declared using {% set %}.

Updating your example:

# collection_of_jinja_macros.jinja

{% include 'path/macro1.jinja' as macro1 %}
{% include 'path/macro2.jinja' as macro2 %}

{% set macro1 = macro1 %}
{% set macro2 = macro2 %}

If you do this, then the following works:

# main.rest

{% import 'path/collection/of_jinja_macros.jinja' as macros %}

{{ macros.macro1.someMacroName() }}
{{ macros.macro2.someOtherMacroName() }}

I wish it were sufficient to use the import ... as syntax.

like image 94
susodapop Avatar answered Mar 19 '26 13:03

susodapop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!