Macros in django templates

In jinja, I can create macros and call them in my template as follows:

{% 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 there is no macro tag in django templates. I am interested in the best way to do something like this in django templates.

+6
source share
4 answers

As you said, macros do not exist in django programming languages.

There are template tags for creating more complex things in templates, but this is not what you are looking for, since the django template system also does not allow passing parameters 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

This is how I will 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 %} ... 
+8
source

template / partial / 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"%} 
+1
source

I found two packages that offer:

they both work the same way: install using pip, type INSTALLED_APPS, {% load macros %} in the template, write and use them.

+1
source

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

0
source

All Articles