<p>可以接受的答案,但我确实建议使用变量名来跟踪节结构。我个人的喜好是<a href="http://docs.djangoproject.com/en/dev/ref/templates/api/?from=olddocs#writing-your-own-context-processors" rel="noreferrer">context processor</a>。例如,如果站点的分区组织透明地反映在url中,请尝试以下操作:</p>
<pre><code># It may be convenient to make this function live in or near your url conf.
def convert_url_path_to_folder_path(path):
# fill in the magic here
def sub_folder_available(request):
folder = convert_url_path_to_folder_path(request.path)
return {'subsection': folder, 'local_base':folder+'/base.html'}
</code></pre>
<p>然后在你的模板中,只需调用</p>
<pre><code>{% extends local_base %}
</code></pre>
<p>可能还有很多其他方法可以做到这一点,但最主要的是要考虑避免将文件夹名称硬编码到模板中。这将为您带来很多里程,特别是因为您可以拖放模板之间的部分,如果他们碰巧足够相似。您还可以添加insert:</p>
<pre><code>def sub_folder_available(request):
folder = convert_url_path_to_folder_path(request.path)
# Check if local base exists:
if os.access(folder+'/base.html',os.F_OK):
base = folder+'/base.html'
else:
# revert to your global base
base = 'base.html'
return {'subsection': folder, 'base':base}
</code></pre>
<p>这种策略的好处当然是,您可以在不使用任何本地基本模板的情况下启动并运行fly weight部分。</p>