1. 程式人生 > >039:模版結構優化之include標籤詳解

039:模版結構優化之include標籤詳解

 引入模版:

有時候一些程式碼是在許多模版中都用到的。如果我們每次都重複的去拷貝程式碼那肯定不符合專案的規範。一般我們可以把這些重複性的程式碼抽取出來,就類似於Python中的函式一樣,以後想要使用這些程式碼的時候,就通過 include 包含進來。這個標籤就是 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 標籤包含模版,會自動的使用主模版中的上下文,也即可以自動的使用主模版中的變數。如果想傳入一些其他的引數,那麼可以使用 with 語句。示例程式碼如下:

# header.html
<p>使用者名稱:{{ username }}</p>


# main.html
{% include "header.html" with username='你大爺' %}
注:這裡的username和你大爺之間的等號之間不能有空格

例項工程截圖如下:

1、urls.py:

2、front.views:

3、index.html:

 4、header.html:

5、footer.html:

 6、company.html:

 

 7、school.html: