Django從理論到實戰(part22)--include模板標籤

學習筆記,僅供參考

參考自:Django打造大型企業官網–Huang Y;

本系列Blog以應用爲主,理論基礎部分我在後端專欄Django系列博客已經寫過了,如果有些需要補充的知識點,我會在這個系列中,儘量詳細的記錄一下。



include模板標籤


理論


有時候一些代碼是在許多模版中是可以複用的,一般我們可以把這些重複性的代碼抽取出來,就類似於Python中的函數一樣,以後想要使用這些代碼的時候,就通過include導入進來,例如:

# header.html
<p>我是header</p>

# footer.html
<p>我是footer</p>

# main.html
{% include 'header.html' %}
<p>我是main內容</p>
{% include 'footer.html' %}

include標籤尋找路徑的方式,和render函數尋找模板路徑的方式是一樣的。

include標籤包含的模版,會自動的使用主模版中的變量,如果想傳入一些其他的參數到include標籤包含的模板中,那麼可以使用with語句:

# header.html
<p>用戶名:{{ username }}</p>

# main.html
{% include "header.html" with username='huangyong' %}

實踐


  • 創建模板

首先,我們在templates文件夾下創建4個模板文件header.html, footer.html, index.html, bookstore.html:


index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {% include 'header.html' %}
    <div class="content">
        這是中間內容{{ username }}
    </div>
    {% include 'footer.html' %}
</body>
</html>

bookstore:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {% include 'header.html' with username='Bai' %}
    <div class="content">
        這是書店的內容
    </div>
    {% include 'footer.html' %}
</body>
</html>

header.html:

<header>
    <ul>
        <li><a href="/">首頁</a></li>
        <li><a href="{% url 'bookstore' %}">書店</a></li>
        <li>{{ username }}</li>
    </ul>
</header>

footer.html:

<footer>
    這是footer部分
</footer>

  • 發起請求

向http://127.0.0.1:8000/發起請求:


點擊書店:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章