如何使用Django的“包含标记”来根据提供给View的参数来提取动态模板?
我正在为我的网站上的内容创建一个“下载”页面。可以下载许多不同的内容,我只想使用一个视图从urls.py获取可选参数的下载页面:
urls.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'
}
),views.py
def download(request, name, title, url, upsell):
return render(request, 'base/pages/download/download.html', {
'title': title,
'url': url,
'upsell': upsell,
}
)download.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‘参数中指定的页面动态填充--如下所示:
download.html第2部分
{% upsell %}然后,我希望根据指定的'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这样,如果指定“upsel-1”,则提供“upsel-1.html”模板;如果指定“upsel-2”,则提供“upsel-2.html”模板。
然而,当我做上面的工作时,我得到了一个TemplateError。有什么简单的方法可以像我上面所做的那样动态地提供一个模板吗?
发布于 2016-11-09 22:24:54
弄明白了!为了解决这个问题,我完全放弃了包含标记,使用了vanilla {% include %}标签,它直接提取外部模板的内容,并在当前模板的上下文中传递。
我的代码现在看起来如下:上面的urls.py和views.py保持不变。在base_extras.py中不需要任何代码。只有download.html被更改:
download.html
<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>
{% include upsell %}https://stackoverflow.com/questions/40498091
复制相似问题