In a Django template, I use a for loop
to display content.
This content is of 3 types. Each type has its own set of conditions, HTML and CSS.
I felt including all that processing in 1 template would make it tough to maintain the file. So instead I'm using template tags:
{% load get_display_type_1 %}
{% load get_display_type_2 %}
{% load get_display_type_3 %}
{% for item in content %}
{% if item == '1' %}
{% display_type_1 payload='foo' %}
{% elif item == '2' %}
{% display_type_2 payload='bar' %}
{% elif item == '3' %}
{% display_type_3 payload='foo bar' %}
{% endif %}
{% endfor %}
And where, for example, the template tag called display_type_1
has the following code:
from django import template
register = template.Library()
@register.inclusion_tag(file_name='display_type_1.html')
def display_type_1(payload):
return {'payload':payload}
Standard stuff so far.
But now take a look at the HTML template connected to the template tag:
{% load myfilter %}
<div class="type1">{{ payload|myfilter }}</div>
I.e. notice I'm loading a custom filter called myfilter
here.
So here's the problem: in essence, I've called {% load myfilter %}
within a for loop. How? Because the template tag itself resides in the parent template's for loop.
This has slower performance then if I had written everything in the parent template and loaded the filter once.
I don't ideally want to abandon using template tags in this way; I find it more maintainable. But I don't want to sacrifice performance by loading filters (etc.) in a for loop either.
Can someone help me improve this pattern, making it more optimal? An illustrative example would be great.
Note: this is a simplified example, the actual code is more complex