2011-08-22 141 views
1

假設我想在我的網站上重複一些簡單的HTML結構很多次。例如,我想在「綠色框」中顯示頁面的某些部分。Pageparts擴展模板

第一個必不可少的步驟來實現這一目標將是創建一個模板文件是這樣的:

<!-- greenbox.html --> 
<div style="background-color:#88ff88;"><br> 
{% block content %}<br> 
{% endblock %}<br> 
</div> 

每當我需要這個預定義模板的時間我要創建像下面這樣的單獨的模板:

<!-- pagepart_1.html --> 
{% extends "greenbox.html" %} 
{% block content %} 
This time I want to add this dummy text in here 
{% endblock %} 

<!-- pagepart_2.html --> 
{% extends "greenbox.html" %} 
{% block content %} 
The second time I want to add some other text 
{% endblock %} 

含有的綠框看起來像這樣的實際頁面:

<html><head>My Page</head> 
<body> 
<h1>Page Title</h1> 
{% include "pagepart_1.html" %} 
<br /><br /> 
{% include "pagepart_2.html" %} 
</body></html> 

這種方法確實有效,但我認爲它包含了一點開銷。 我可以避免爲每個實例創建單獨的模板(pagepart_1.html,pagepart_2.html,...)嗎?

那麼我可以讓我的主頁看起來像這樣嗎?

​​

非常感謝!

回答

0

這是您希望允許完全自定義內容區域的唯一方法。但是,如果你能規範的內容,使得它總是會顯示一個無序列表,例如,你可以這樣做:

<!-- greenbox.html --> 
<div style="background-color:#88ff88;"><br> 
    <ul> 
     {% for item in list %} 
     <li>{{ item }}</li> 
     {% endfor %} 
    </ul> 
</div> 

,然後在模板:

<!-- mypage.html --> 
{% with something as list %} 
    {% include 'greenbox.html' %} 
{% endwith %} 

你可以做多更復雜的結構,甚至通過多個變量(在Django 1.3+):

<!-- greenbox.html --> 
<div style="background-color:#88ff88;"><br> 
    <h2>{{ title }}</h2> 
    <img style="float:{{ float }};" src="{{ image }}" alt="{{ alt_text }}"> 
    <p>{{ description }}</p> 
</div> 

<!-- mypage.html --> 
{% with title=obj.title image=obj.image.name alt_text=obj.title float="left" description=obj.description %} 
    {% include 'greenbox.html' %} 
{% endwith %} 
+0

謝謝。其實我確實想要完全可定製的區域。因此,標準化內容不適合我。以下方法也可以應用:[鏈接](https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#parsing-until-another-block-tag-and-saving-contents )但它也帶來了一些開銷。 – user893736

0

我會寫發出的HTML自定義標籤,並多次使用它。