Django inclusion tag with configurable template

Viewed 9046

I've created an inclusion tag, however I'd like to be able to make the template optionally configurable. There doesn't seem to be support for this out of the box, so I'd like to see how people did this - maybe a method search the templates directory first for a specific template name and then falling back to the default template.

@register.inclusion_tag('foo.html', takes_context=True)
5 Answers

A solution could be a regular inclusion_tag which pass dynamic template name to context.

Like this :

# templatetags/tags.py

@register.inclusion_tag('include_tag.html', takes_context=True)
def tag_manager(context):
    context.update({
        'dynamic_template': resolve_template(context),
    })
    return context

And the template:

<!-- include_tag.html -->

{% include dynamic_template %}

The tricks here is, when I call {% tag_manager %}, it includes include_tag.html which in turn includes the template returned by resolve_template() (not included for brevity).

Hope this helps...

Related