2016-11-08 110 views
0

如何使用Django的「包含標籤」根據提供給View的參數來拉動態模板?如何在Django中註冊一個「動態」包含標籤?

我正在爲我的網站上的內容創建一個「下載」頁面。許多不同的內容可以下載,我想用只有我一個,在可選參數提取從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' 
    } 
), 

意見。 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頁面的底部,我想有一個包含標籤動態填充總部設在「追加銷售」放慢參數指定的頁面上 - 這是沿着這些線路:

download.html第2部分

{% upsell %} 

我再想這個標籤T Ø從我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 

這樣,如果「向上銷售-1」規定,提供「upsell-1.html」模板;如果指定了「upsell-2」,則提供「upsell-2.html」模板。

但是,當我這樣做時,我得到一個TemplateError。是否有一種簡單的方式來動態提供模板,就像我上面要做的那樣?

+0

[這個問題(可能的重複http://stackoverflow.com/questions/1490059/django-inclusion-tag-with-配置模板) – Alasdair

回答

0

想通了!爲了解決這個問題,我完全拋棄了包含標籤,並使用了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 %}