Getting template name in django template

For debugging purposes, I would like to have a variable in all my templates containing the path to the rendered template. For example, if the view displays the /account/logout.html templates, I would like to {{template_name}} contain the string templates /account/logout.html.

I don’t want to go and change any views (especially because I reuse many applications), so the path seems to be a context processor that is up to something. The question is what can be understood.

Or maybe it's built-in, and I don't know about that?

+4
source share
2 answers

A simple way:

Download and use the django debug toolbar . You will get an approximation of what you need, and even more.

Less easy way:

Replace Template.render with django.test.utils.instrumented_test_render , listen for the django.test.signals.template_rendered signal and add the template name to the context. Note that TEMPLATE_DEBUG must be true in your settings file or there will be no source from which to get the name.

 if settings.DEBUG and settings.TEMPLATE_DEBUG from django.test.utils import instrumented_test_render from django.test.signals import template_rendered def add_template_name_to_context(self, sender, **kwargs) template = kwargs['template'] if template.origin and template.origin.name kwargs['context']['template_name'] = template.origin.name Template.render = instrumented_test_render template_rendered.connect(add_template_name_to_context) 
+8
source

Templates are just strings, not file names. Probably your best option is to render_to_response monkey monkey render_to_response and / or direct_to_template and copy the arg file name into context.

+1
source

All Articles