Django之模板繼承,django模板

來源:互聯網
上載者:User

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模板。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.