[Answered ]-Django Template: include another html template, but only once

1👍

You could create a custom template tag. Create a templatetags directory in the same root as your models.py and views.py. In there, create a custom_tags.py and register a custom tag that will look at the list of currently included templates, and ignore the current template if it was already included:

from django import template
from django.template.loader import render_to_string

register = template.Library()


@register.simple_tag(takes_context=True)
def include_once(context, template_name):
    if 'included_templates' not in context.dicts[0]:
        context.dicts[0]['included_templates'] = set()

    if template_name not in context.dicts[0]['included_templates']:
        context.dicts[0]['included_templates'].add(template_name)
        return render_to_string(template_name, context.flatten())
    else:
        return ""

Now in your templates load your custom tags and use the new include_once tag:

{% load custom_tags %}
{% include_once "embed_data_foo.html" %}
{% include_once "embed_data_foo.html" %}
{% include_once "embed_data_foo.html" %}

The only issue I can think with this is that it might use a lot of memory server-side if you have a large number of templates and/or high traffic.

Leave a comment