2014-03-25 26 views
0

假設我有一個簡單的代碼片段,我想都在我的網站上重複(以及每頁有時多次):包括在模板中的動態片段多次

<div class="snippet-css"> 
    <h1>{% block snippet-header %}{% endblock %}</h1> 

    <div class="snippet-content"> 
    {% block snippet-content %} 
    {% endblock %} 
    </div> 

    <div class="snippet-footer"> 
    {% block snippet-footer%}{% endblock %} 
    </div> 
</div> 

我想包括這個片段多次在同一個頁面中,每次都用獨特的內容替換片段標題,片段內容和片段腳註塊。

定義Django的標籤,它會接受兩三個區塊作爲參數不好看,我(Django的標籤裏面反鎖HTML代碼):

{% generate_snippet heading content footer %} 

我也發現這個博客帖子

http://powertwenty.com/blog/index.php/python/repeating_sections_in_a_django_template

其通過分割片段到多個變量的問題涉及。

什麼是實現這個結果與Django模板的最佳方式?

回答

4

可以值傳遞給Django的內置{% include %}模板標籤是這樣的:

{% include "snippet.html" with header="blah" content="content" footer="lalala" %} 

您也可以傳遞變量:

{% include "snippet.html" with header=var1 content=var2 footer=var3 %} 

然後在snippet.html:

<div class="snippet-css"> 
    <h1>{{ header }}</h1> 

    <div class="snippet-content"> 
    {{ content }} 
    </div> 

    <div class="snippet-footer"> 
    {{ footer }} 
    </div> 
</div> 

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#include

+0

這可以工作,如果有在Django的方式如何定義模板中的變量(即是純HTML和模板代碼的多組合)。例如。 snippet-content可能會變得非常複雜(包含for循環和誰知道其他的魔法)。 – Enuy

0

一個更好的選擇是使用inclusion tag - 你可以定義你的標籤喜歡的任何變量,他們將到模板片段被傳遞進行渲染。