Reuse a block of code in several places in jinja2


I have this html snippet which needs to be used in lots of places in the jinja2 templates:

<div class="usedalot">{{  somevalue }}</div>

for example, in template1.html, template2.html. template3.html, this code is repeated several places

<!-- template1.html, template2.html. template3.html -->
<div class="usedalot">{{  somevalue }}</div>
<div class="usedalot">{{  somevalue }}</div>
<div class="usedalot">{{  somevalue }}</div>

Instead of copying and pasting, is there someway to use this code snippet as a block? The jinja2 template inheritance (with blocks) do not seem to solve this problem.


What you are looking for is called a macro.

Macros are placed in separate files (e.g., macros.html).

{% macro usedalot(somevalue) %}
    <div class="usedalot">{{ somevalue }}</div>
{% endmacro %}

You can then import your macros in other templates

{% from 'macros.html' import usedalot %}

and then use them whenever needed

{{ usedalot(1) }}

This will output

<div class="usedalot">1</div>

Answered By – dirn

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published