Django从理论到实战(part22)--include模板标签
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                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/發起請求:
點擊書店:
總結
以上是生活随笔為你收集整理的Django从理论到实战(part22)--include模板标签的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 口袋妖怪:太阳/月亮神兽及究极异兽捕捉方
- 下一篇: LGD战队LOL队员名单2021
