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.
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 %}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With