include & extends

      在〈include & extends〉中尚無留言

一個網站當然不可能只有一個網頁,若每個網頁的內容大致相同的話,那重複撰寫相同的 html 碼實在很煩人,所以就可以使用 include 或 extends 來複製相同的部份。

include tag

首先將每個網頁相同的頭尾寫在 head.html 及 tail.html 裏,並將二個檔案置於 templates 目錄中

head.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>MahalJSP</title>
</head>
<body leftmargin="0" topmargin="0" rightmargin="0" topmargin="0">
<table border="1" cellpadding="0" cellspacing="0" width="98%" align="center">
<tr>
<td>

tail.html

            </td>
</tr>
</table>
</body>
</html>

然後在 templates 目錄下新增 first.html,內容如下

{% include "head.html" %}
測試
{% include "tail.html" %}

最後使用 python manager.py startapp first 新增 first app,然後於 first 目錄下新增 first.py 檔案,內容如下

from django.shortcuts import render
def html(request):
return render(request, 'first.html')

當然 setting.py 及 urls.py 也要進行設定,此時輸入 localhost:7000/first 即可看到網頁內容了。日後要新增其它網頁,只要新網頁前後新增 include tag即可。

extends

另一種方式,是先撰寫 base.html,然後新網頁繼承 base.html,不同處使用 block 區隔出來。首先在templates 目錄下新增 base.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>MahalJSP</title>
</head>
<body leftmargin="0" topmargin="0" rightmargin="0" topmargin="0">
<table border="1" cellpadding="0" cellspacing="0" width="98%" align="center">
<tr>
<td>
{% block content1 %}
{% endblock %}
</td>
</tr>
<tr>
<td>
{% block content2 %}
{% endblock %}
</td>
</tr>
</table>
</body>
</html>

上述的 “content1” 及 “content2” 為區塊的名稱,可以隨意命名。然後在 templats 目錄下新增 second.html,內容如下

{% extends 'base.html' %}
{% block content1 %}
區塊1
{% endblock %}

{% block content2 %}
區塊2
{% endblock %}

同樣產生 second.py app並設定setting.py及urls.py,即可看到新增的網頁

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *