Check if a template exists within a Django template

pq. picture pq. · Jun 2, 2011 · Viewed 7.6k times · Source

Is there an out-of-the-box way of checking if a template exists before including it in a Django template? Alternatives are welcome too but some of them would not work due to the particular circumstances.

For example, here's an answer to a slightly different question. This is not what I'm looking for: How to check if a template exists in Django?

Answer

Chris Pratt picture Chris Pratt · Jun 2, 2011

Assuming include doesn't blow up if you pass it a bad template reference, that's probably the best way to go. Your other alternative would be to create a template tag that essentially does the checks in the link you mentioned.

Very basic implementation:

from django import template

register = template.Library()

@register.simple_tag
def template_exists(template_name):
    try:
        django.template.loader.get_template(template_name)
        return "Template exists"
    except template.TemplateDoesNotExist:
        return "Template doesn't exist"

In your template:

{% template_exists 'someapp/sometemplate.html' %}

That tag isn't really all that useful, so you'd probably want to create one that actually adds a variable to the context, which you could then check in an if statement or what not.