with/include template pattern? seeking best practices

26 views
Skip to first unread message

Ivan Kirigin

unread,
Sep 4, 2012, 6:21:47 PM9/4/12
to django...@googlegroups.com
I find myself writing things like this a lot in django templates

{% for e in some_list %}
    {% with e as element %}
        {% include "single_element.html" %}
    {% endwith %} 
{% enfor %}

This would be in a template which shows a lists of elements, with another template that renders a single one. The template single_element.html uses element locally. I find this encapsulates my templates well, especially in making single_element.html far more reusable.

I've been doing this for a while and wanted to know if there is a better way I just don't know about. Also, I don't know the performance implications of so many with/include calls. This list could be very long (100s or 1000s).

Thanks!
Ivan Kirigin

e.generalov

unread,
Sep 5, 2012, 3:21:28 AM9/5/12
to django...@googlegroups.com
{% for e in some_list %}
        {% include "single_element.html" with element=e %}
{% enfor %}

Mike S

unread,
Sep 5, 2012, 5:23:55 AM9/5/12
to django...@googlegroups.com
The code `e.generalov` gave has been valid since Django 2.3: <https://docs.djangoproject.com/en/dev/ref/templates/builtins/#include>

For more complicated context, you can also write an inclusion tag <https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags> and use that to render the inner template.
Reply all
Reply to author
Forward
0 new messages