Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the template name in django template

Tags:

python

django

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

I don't want to go and change any views (specially because I'm reusing a lot of apps), so the way to go seems to be a context processor that introspects something. The question is what to introspect.

Or maybe this is built in and I don't know about it?

like image 557
rz. Avatar asked May 13 '09 17:05

rz.


People also ask

How do I get templates in Django?

To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.

What does {{ name }} this mean in Django templates?

8. What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What is template tag Django?

The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client. template.html : <ul> {% for x in mymembers %} <li>{{ x. firstname }}</li> {% endfor %} </ul> Run Example »


1 Answers

The easy way:

Download and use the django debug toolbar. You'll get an approximation of what you're after and a bunch more.

The 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 name of the template to the context. Note that TEMPLATE_DEBUG must be true in your settings file or there will be no origin 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)
like image 140
Baldu Avatar answered Sep 21 '22 23:09

Baldu