Jinja templates, how to do an import of all macros to follow the DRY principle?

Viewed 1549

currently I have in many places:

{% from "macros/render_product_materials.html" import render_product_materials %}
{% from "macros/render_citation.html" import render_citation %}
{% from "macros/render_product_packages.html" import render_product_packages %}
{% from "macros/render_icon_explanation_section.html" import render_icon_explanation_section %}
{% from "macros/render_percentage_items.html" import render_percentage_items %}

this list goes on!

then i call the code in the template:

{{render_percentage_items('some args',2,34,55)}}

If I change a function name, I have to change it everywhere, if I add a new function, I have to go and import it each time everywhere

I rather just want to do this, something like this:

{% include 'macros/all_macros.html' %}

then I just put all imports into all_macros.html

But: the imports do not get available in the context

e.g.

{% include 'macros/all_macros.html' %}

{{render_percentage_items('some args',2,34,55)}}

doesn't work. render_percentage_items not found. Now what is the way to do this the jinja way?

1 Answers

Collecting related macros into a single file is a start. Then use import … as rather than include.

{% import 'macros/all_macros.html' as m %}
{{ m.render_percentage_items('some args', 2, 34, 55) }}

So, basically, exactly what SumanKalyan already said.

In many (most?) cases, you won't even need the with context, but you can refer here to decide if maybe you do. As mentioned in the documentaiton, with context disables caching, and usually imported templates only contain macros anyway, which can and should be cached.

Reference.

Related