Django从理论到实战(part22)--include模板标签
生活随笔
收集整理的這篇文章主要介紹了
Django从理论到实战(part22)--include模板标签
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
學(xué)習(xí)筆記,僅供參考
參考自:Django打造大型企業(yè)官網(wǎng)–Huang Y;
本系列Blog以應(yīng)用為主,理論基礎(chǔ)部分我在后端專欄的Django系列博客已經(jīng)寫過了,如果有些需要補充的知識點,我會在這個系列中,盡量詳細的記錄一下。
include模板標簽
理論
有時候一些代碼是在許多模版中是可以復(fù)用的,一般我們可以把這些重復(fù)性的代碼抽取出來,就類似于Python中的函數(shù)一樣,以后想要使用這些代碼的時候,就通過include導(dǎo)入進來,例如:
# header.html <p>我是header</p># footer.html <p>我是footer</p># main.html {% include 'header.html' %} <p>我是main內(nèi)容</p> {% include 'footer.html' %}include標簽尋找路徑的方式,和render函數(shù)尋找模板路徑的方式是一樣的。
include標簽包含的模版,會自動的使用主模版中的變量,如果想傳入一些其他的參數(shù)到include標簽包含的模板中,那么可以使用with語句:
# header.html <p>用戶名:{{ username }}</p># main.html {% include "header.html" with username='huangyong' %}實踐
- 創(chuàng)建模板
首先,我們在templates文件夾下創(chuàng)建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">這是中間內(nèi)容{{ 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">這是書店的內(nèi)容</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>- 發(fā)起請求
向http://127.0.0.1:8000/發(fā)起請求:
點擊書店:
總結(jié)
以上是生活随笔為你收集整理的Django从理论到实战(part22)--include模板标签的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 口袋妖怪:太阳/月亮神兽及究极异兽捕捉方
- 下一篇: R语言观察日志(part5)--利用re