Django之模板繼承,django模板
在使用Django進行web開發時,往往會構造一個基礎架構模板即base.html,而後在其子模板中對它所包含網站公用部分和定義塊進行重載。
首先建立一個base.html,源碼為:
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>{% block title %}{% endblock %}</title></head><body><h1>My helpful timestamp site</h1>{% block content %}{% endblock %}{% block footer %}<hr><p>Thanks for visiting my site.</p>{% endblock%}</body></html>這個叫做base.html的模板定義了一個簡單的html架構文檔,等會我們將在我們的網站中的頁面使用它。子模板的作用就是重載、添加
或保留那些塊的內容。
現在建立一個current_datetime.html模板來使用它:
{% extends "base.html" %}{% block title %}The current time{% endblock %}{% block content %}<p>It is now {{current_date }}.</p>{% endblock %}再建立一個hours_ahead.html模板,源碼為:
{% extends "base.html" %}{% block title %}Future time{% endblock %}{% block content %}<p>In {{hour_offset }} hour(s),it will be {{next_time}}.</p>{% endblock %}上面的部分非html標籤等會再來解釋它,現在在views.py中建立兩個函數,index4,與index5,分別對應這兩個模板。源碼為:
def index4(req,offset): offset=int(offset) next_time=datetime.datetime.now()+datetime.timedelta(hours=offset) return render_to_response("hours_ahead.html",{'hour_offset':offset,'next_time':next_time})def index5(req): now=datetime.datetime.now() return render_to_response('current_datetime.html',{'current_date':now})在url中的配置為:
url(r'^hours_ahead/(\d{1,2}$)','blog.views.index4'), url(r'^current_datetime/$','blog.views.index5'),現在啟動伺服器,在瀏覽器中查看效果,current_datetime.html為:
hours_ahead.html中的效果為:
如此兩個html效果就顯示出來了,同時也解釋一下base.html中所起的作用,兩個html中都使用了{% extends %}標記,
這個就是繼承base.html中的內容,在使用{ % block XXXXX %} {% endblock%}時,中間的內容便是插入在使用了base.html兩個標籤的
中間,由此便極大的避免了代碼的冗餘。每個模板只包含自己獨一無二的代碼,無需多餘的部分,而如果想要進行網站級的設計修改,僅需
修改base.html,所有其他模板會立即反映出所做修改。
上述,便是django之繼承使用base.html模板。