<p>在源代码中,虽然<a href="https://code.djangoproject.com/browser/django/trunk/django/template/base.py?rev=17133#L115" rel="nofollow noreferrer">^{<cd1>}</a>对象可以访问模板名(通过<code>.name</code>),但此值从未传递给<a href="https://code.djangoproject.com/browser/django/trunk/django/template/base.py?rev=17133#L230" rel="nofollow noreferrer">Parser</a>对象,因此不能用于模板标记。</p>
<p>有多种方法可以使模板名称对模板本身可用(通过将其添加到上下文中),但不在模板标记内。</p>
<p>正如丹尼尔·罗斯曼在评论中提到的,如果你能详细说明你真正想要达到的目标,也许有更好的方法来实现你想要的目标。没有冒犯,但听起来可能是<a href="https://meta.stackexchange.com/q/66377/134327">XY problem</a>。</p>
<hr/>
<p>出于对学术的兴趣,我急忙摆弄了一下,看是否有可能。据我所见,这是可能的,但不是没有改变或猴子补丁的django源。</p>
<p><em>注意:以下不是建议的解决方案,只是提示实际工作可能需要什么。不用于生产代码。</em></p>
<p>通过使用以下更改修改<code>django.template.base.py</code>,我们将<code>.template_name</code>属性添加到parser对象,使其可用于模板标记。</p>
<ol>
<li><a href="https://gist.github.com/1388704#L144" rel="nofollow noreferrer">Added optional arg to ^{<cd5>}</a></li>
<li><a href="https://gist.github.com/1388704#L153" rel="nofollow noreferrer">Added template name as extra attribute to parser</a></li>
<li><a href="https://gist.github.com/1388704#L125" rel="nofollow noreferrer">Passed in the template name when calling ^{<cd6>}</a></li>
</ol>
<p>为了测试这一点,我定义了以下标记,它只返回大写的模板名称:</p>
<pre><code>from django.template.base import Node, Library
register = Library()
class TemplateNameNode(Node):
def __init__(self, template_name):
self.name = template_name
def render(self, context):
return self.name.upper()
@register.tag
def caps_template_name(parser, token):
return TemplateNameNode(parser.template_name)
</code></pre>
<p>以及以下模板:</p>
<pre><code>{% load mytags %}
Template name in caps: {% caps_template_name %}
</code></pre>
<p>当在<code>./manage.py shell</code>中测试时,这似乎有效:</p>
<pre><code>>>> from django.template import loader, Context
>>> t = loader.get_template("test.html")
>>> t.render(Context({}))
u'\nTemplate name in caps: TEST.HTML\n'
</code></pre>
<p>虽然这似乎是可行的,但我应该重申,手动修补django源代码<strong>永远不是一个好的解决方案,而且在迁移到不同版本时会遇到各种各样的麻烦。</p>