<p>您也许可以使用上下文处理器来实现这一点,但我不确定这些处理器是否可以访问模板的名称。</p>
<p>接下来的工作是为您所做的呈现调用制作一个包装器。假设您当前正在执行以下操作:</p>
<pre><code>from django.shortcuts import render
def index(request):
return render(request, 'app/index.html', { 'foo': 'bar', })
</code></pre>
<p>如果为此创建自己的包装器,则可以在实际呈现之前将模板名称添加到字典中:</p>
<pre><code>from django.shortcuts import render
def myrender(request, template, dictionary):
dictionary.update({'template_name': template})
return render(request, template, dictionary)
</code></pre>
<p>然后在您的视图中,按如下方式更改它(假设您将上面的函数保存在<code>myutils.py</code>中,并且它在您的路径上可用):</p>
<pre><code>#from django.shortcuts import render <- delete this line
from myutils import myrender as render
def index(request):
return render(request, 'app/index.html', { 'foo': 'bar', })
</code></pre>
<p>现在所有的<code>render</code>调用都将用模板名更新字典。在任何模板中,只需使用<code>{{ template_name }}</code>获取名称。当然,您也可以以类似的方式更新其他呈现函数,如<code>render_to_response</code>等。</p>
<p>而且,<code>import myrender as render</code>稍后可能会或不会让您感到困惑,因为它的名称类似于Django函数。。。如果是,只需导入它而不使用“<code>as render</code>”,并用<code>myrender</code>替换所有的<code>render</code>调用。就我个人而言,我更喜欢这样,因为这使得它可以取代现有的呈现函数。</p>