歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Django之模板繼承

Django之模板繼承

日期:2017/3/1 9:30:29   编辑:Linux編程

在使用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模板。

Ubuntu Server 12.04 安裝Nginx+uWSGI+Django環境 http://www.linuxidc.com/Linux/2012-05/60639.htm

Django+Nginx+uWSGI 部署 http://www.linuxidc.com/Linux/2013-02/79862.htm

Django實戰教程 http://www.linuxidc.com/Linux/2013-09/90277.htm

Django Python MySQL Linux 開發環境搭建 http://www.linuxidc.com/Linux/2013-09/90638.htm

Django 的詳細介紹:請點這裡
Django 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved