Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macros in django templates

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.

like image 964
Dima Kudosh Avatar asked Jul 25 '15 19:07

Dima Kudosh


1 Answers

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 %}
...
like image 121
Chris Schäpers Avatar answered Sep 28 '22 05:09

Chris Schäpers