【问题标题】:Getting the template name in django template在 django 模板中获取模板名称
【发布时间】:2009-05-13 17:34:35
【问题描述】:

出于调试目的,我希望在所有模板中都有一个变量来保存正在呈现的模板的路径。例如,如果视图呈现 templates/account/logout.html,我希望 {{ template_name }} 包含字符串 templates/account/logout.html。

我不想去更改任何视图(特别是因为我正在重用很多应用程序),所以要走的路似乎是一个内省的上下文处理器。问题是要自省什么。

或者也许这是内置的,我不知道?

【问题讨论】:

    标签: python django


    【解决方案1】:

    简单的方法:

    下载并使用django debug toolbar。你会得到你所追求的近似值和更多。

    不太简单的方法:

    Template.render 替换为django.test.utils.instrumented_test_render,监听django.test.signals.template_rendered 信号,并将模板名称添加到上下文中。请注意,TEMPLATE_DEBUG 在您的设置文件中必须为真,否则将无法获取名称。

    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)
    

    【讨论】:

      【解决方案2】:

      模板只是字符串而不是文件名。可能您最好的选择是修补 render_to_response 和/或 direct_to_template 并将文件名 arg 复制到上下文中。

      【讨论】:

        【解决方案3】:

        来自Django 1.5 release notes

        基于类的视图上下文中的新视图变量

        在所有通用的基于类的视图(或任何从ContextMixin 继承的基于类的视图)中,上下文字典包含一个指向View 实例的view 变量。

        因此,如果您使用基于类的视图,则可以使用

        {{ view.template_name }}
        

        如果 template_name 被显式设置为视图的属性,则此方法有效。

        否则,你可以使用

        {{ view.get_template_names }}
        

        获取模板列表,例如['catalog/book_detail.html'].

        【讨论】: