在django模板中获取模板名称 [英] Getting the template name in django template

查看:124
本文介绍了在django模板中获取模板名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了进行调试,我想在所有模板中都有一个变量,其中包含正在呈现的模板的路径。例如,如果视图呈现模板/ account / logout.html,我希望{{template_name}}包含字符串templates / account / logout.html。

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?

推荐答案

简单的方法

下载并使用 django调试工具栏

不太简单的方法

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

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)

这篇关于在django模板中获取模板名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆