如何使用 Django 的“包含标签”根据提供给视图的参数提取动态模板?
我正在为我的网站上的内容创建一个“下载”页面。可以下载许多不同的内容,我只想为下载页面使用一个视图,该视图从 urls.py 中提取可选参数:
网址.py
url(r'^download/download-1/$', base_views.download, {
'name':'download-1',
'title':'Download 1',
'url':'https://sample-download-location.com/download-1.zip',
'upsell':'upsell-1'
}
),
url(r'^download/download-2/$', base_views.download, {
'name':'download-2',
'title':'Download 2',
'url':'https://sample-download-location.com/download-2.zip',
'upsell':'upsell-2'
}
),
视图.py
def download(request, name, title, url, upsell):
return render(request, 'base/pages/download/download.html', {
'title': title,
'url': url,
'upsell': upsell,
}
)
下载.html 第 1 部分
然后,来自该视图的信息将通过管道传输到下载模板中,如下所示:
<div id="thank-you-content">
<div class="wrapper">
<h1>Download <em>{{ title }}</em></h1>
<p>Thanks for purchasing <em>{{ title }}</em>! You can download it here:</p>
<p><a target="_blank" class="btn btn-lg btn-success" href="{{ url }}">Download Now</a></p>
<p>And afterwards, be sure to check out...</p>
</div>
</div>
这是棘手的部分:在 download.html 页面的底部,我想要一个包含标签,该标签根据“upsell”参数中指定的页面动态填充 - 类似于以下内容:
下载.html 第 2 部分
{% upsell %}
然后,我希望根据指定的“追加销售”页面动态地从我的 base_extras.py 文件中提取此标签:
base_extras.py
@register.inclusion_tag('base/pages/upsell-1.html')
def upsell_1_content():
return
@register.inclusion_tag('base/pages/upsell-2.html')
def upsell_2_content():
return
这样,如果指定了“upsell-1”,则提供“upsell-1.html”模板;如果指定了“upsell-2”,则提供“upsell-2.html”模板。
但是,当我执行上述操作时,我得到一个 TemplateError。有没有一种简单的方法可以像我在上面尝试做的那样动态地提供模板?