Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a template exists within a Django template

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?

like image 873
pq. Avatar asked Jun 02 '11 15:06

pq.


4 Answers

I encountered this trying to display a template only if it exists, and wound up with the following template tag solution:

Include a template only if it exists

Put the following into yourapp/templatetags/include_maybe.py

from django import template
from django.template.loader_tags import do_include
from django.template.defaulttags import CommentNode
register = template.Library()

@register.tag('include_maybe')
def do_include_maybe(parser, token):
    "Source: http://stackoverflow.com/a/18951166/15690"
    bits = token.split_contents()
    if len(bits) < 2:
        raise template.TemplateSyntaxError(
            "%r tag takes at least one argument: "
            "the name of the template to be included." % bits[0])

    try:
        silent_node = do_include(parser, token)
    except template.TemplateDoesNotExist:
        # Django < 1.7
        return CommentNode()

    _orig_render = silent_node.render
    def wrapped_render(*args, **kwargs):
        try:
            return _orig_render(*args, **kwargs)
        except template.TemplateDoesNotExist:
            return CommentNode()
    silent_node.render = wrapped_render
    return silent_node

Access it from your templates by adding {% load include_maybe %} at the top of your template, and using {% include_maybe "my_template_name.html" %} in code.

This approach has the nice side effect of piggy-backing the existing template include tag, so you can pass in context variables in the same way that you can with a plain {% include %}.

Switch based on whether a template exists

However, I wanted some additional formatting on the embedding site if the template existed. Rather than writing an {% if_template_exists %} tag, I wrote a filter that lets you work with the existing {% if %} tag.

To this end, put the following into yourapp/templatetags/include_maybe.py (or something else)

from django import template
from django.template.defaultfilters import stringfilter


register = template.Library()

@register.filter
@stringfilter
def template_exists(value):
    try:
        template.loader.get_template(value)
        return True
    except template.TemplateDoesNotExist:
        return False

And then, from your template, you can do something like:

{% load include_maybe %}

{% if "my_template_name"|template_exists %}
     <div>
         <h1>Notice!</h1>
         <div class="included">
             {% include_maybe "my_template_name" %}
         </div>
     </div>
{% endif %}

The advantage of using a custom filter over using a custom tag is that you can do things like:

{% if "my_template_name"|template_exists and user.is_authenticated %}...{% endif %}

instead of using multiple {% if %} tags.

Note that you still have to use include_maybe.

like image 43
4 revs, 2 users 85% Avatar answered Nov 14 '22 08:11

4 revs, 2 users 85%


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.

like image 192
Chris Pratt Avatar answered Nov 14 '22 08:11

Chris Pratt


I needed to conditionally include templates if they exist but I wanted to use a variable to store the template name like you can do with the regular {% include %} tag.

Here's my solution which I've used with Django 1.7:

from django import template
from django.template.loader_tags import do_include

register = template.Library()


class TryIncludeNode(template.Node):
    """
    A Node that instantiates an IncludeNode but wraps its render() in a
    try/except in case the template doesn't exist.
    """
    def __init__(self, parser, token):
        self.include_node = do_include(parser, token)

    def render(self, context):
        try:
            return self.include_node.render(context)
        except template.TemplateDoesNotExist:
            return ''


@register.tag('try_include')
def try_include(parser, token):
    """
    Include the specified template but only if it exists.
    """
    return TryIncludeNode(parser, token)

In a Django template it might be used like this:

{% try_include "template-that-might-not-exist.html" %}

Or, if the template name is in a variable called template_name:

{% try_include template_name %}
like image 4
Beau Avatar answered Nov 14 '22 08:11

Beau


include accepts variables:

{% include template_name %}

so you could do the check in your view.

like image 1
arie Avatar answered Nov 14 '22 08:11

arie