Django template tag to retrieve template filename

• 2 min read

One useful Django template tag is to retrieve the template filename from inside the template. Unfortunately, Django built in tags do not provide one for this. However, you can write a simple tag to accomplish this.

Here's are two tags, that return either the base filename or the full filename.

from django import template

register = template.Library()

@register.simple_tag(takes_context=True)
def basefilename(context):
    '''Returns filename minus the extension'''
    return context.template_name.split('.')[0]

@register.simple_tag(takes_context=True)
def fullfilename(context):
    '''Returns full filename with the extension'''
    return context.template_name

To be complete, tthere should be another tag that returns the filename with its entire path. But I haven't figured out how to do this -- at least from within the confines of the template tag framework.