Macros in django templates Macros in django templates python python

Macros in django templates


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


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.


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