Getting the template name in django template

后端 未结 3 1875
遥遥无期
遥遥无期 2020-12-31 23:03

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/accoun

相关标签:
3条回答
  • 2020-12-31 23:31

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

    0 讨论(0)
  • 2020-12-31 23:35

    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)
    
    0 讨论(0)
  • 2020-12-31 23:47

    From Django 1.5 release notes:

    New view variable in class-based views context

    In all generic class-based views (or any class-based view inheriting from ContextMixin), the context dictionary contains a view variable that points to the View instance.

    Therefore, if you're using class-based views, you can use

    {{ view.template_name }}
    

    This works if template_name is explicitly set as an attribute on the view.

    Otherwise, you can use

    {{ view.get_template_names }}
    

    to get a list of templates, e.g. ['catalog/book_detail.html'].

    0 讨论(0)
提交回复
热议问题