Macros in django templates

14,967

Solution 1

As you already said macros don't exist in django's templating languages.

There are template tags to do more difficult things in templates, but that's not what you're looking for either, because django's templating system also doesn't allow parameters being passed to functions.

The best thing for your example would be to use the include tag:
https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#include

Here's how I would use it:

templates/snippets/list.html

<ul>
{% for item in list %}
   <li>{{ item }}</li>
{% endfor %}
</ul>

templates/index.html

{% include 'snippets/list.html' with list=list1 %}
{% include 'snippets/list.html' with list=list2 %}
{% include 'snippets/list.html' with list=list3 %}
...

Solution 2

I found two packages to offer that:

they both look to work the same: install with pip, put in INSTALLED_APPS, {% load macros %} in the template, write and use them.

Solution 3

template/partials/example-partial.html

{%if partial_name == 'partial1'%}
<ul>
{% for item in list %}
   <li>{{ item }}</li>
{% endfor %}
</ul>
{%endif%}


{%if partial_name == 'partial2'%}
<ul>
{% for item in list %}
   <li>{{ item }}</li>
{% endfor %}
</ul>
{%endif%}


{%if partial_name == 'partial3'%}
<ul>
{% for item in list %}
   <li>{{ item }}</li>
{% endfor %}
</ul>
{%endif%}

templates/index.html

{% include 'partials/example-partial.html' with list=list1 partial_name="partial1"%}
{% include 'partials/example-partial.html' with list=list2 partial_name="partial2"%}
{% include 'partials/example-partial.html' with list=list3 partial_name="partial3"%}

Solution 4

... just start using jinja with Django. it's very easy to turn it on and you can use both template engines at the same time, of course for different files.

Share:
14,967
Dima  Kudosh
Author by

Dima Kudosh

Python developer

Updated on June 11, 2022

Comments

  • Dima  Kudosh
    Dima Kudosh almost 2 years

    In jinja I can create macros and call it in my template like this:

    {% macro create_list(some_list) %}
    <ul>
        {% for item in some_list %}
        <li>{{ item }}</li>
        {% endfor %}
    </ul>
    {% endmacro %}
    
    HTML code....
    
    {{ create_list(list1) }}
    {{ create_list(list2) }}
    {{ create_list(list3) }}
    

    I read in django docs that django templates hasn't macro tag. I'm interested in the best way to do something like this in django templates.