1、if/else
{% if %} 標籤檢查(evaluate)一個變量,若是這個變量爲真(即,變量存在,非空,不是布爾值假),系統會顯示在 {% if %} 和 {% endif %} 之間的任何內容,例如:html
{% if today_is_weekend %} <p>Welcome to the weekend!</p> {% endif %} {% else %} 標籤是可選的: {% if today_is_weekend %} <p>Welcome to the weekend!</p> {% else %} <p>Get back to work.</p> {% endif %}
Python 的「真值」python
在python中空的列表 ( [] ),tuple( () ),字典( {} ),字符串( '' ),零( 0 ),還有 None 對象,在邏輯判斷中都爲假,其餘的狀況都爲真。編程
{% if %} 標籤接受 and , or 或者 not 關鍵字來對多個變量作判斷 ,或者對變量取反( not ),例如:緩存
{% if athlete_list and coach_list %} Both athletes and coaches are available. {% endif %} {% if not athlete_list %} There are no athletes. {% endif %} {% if athlete_list or coach_list %} There are some athletes or some coaches. {% endif %} {% if not athlete_list or coach_list %} There are no athletes or there are some coaches. (OK, so writing English translations of Boolean logic sounds stupid; it's not our fault.) {% endif %} {% if athlete_list and not coach_list %} There are some athletes and absolutely no coaches. {% endif %}
{% if %} 標籤不容許在同一個標籤中同時使用 and 和 or ,由於邏輯上可能模糊的,例如,以下示例是錯誤的:app
{% if athlete_list and coach_list or cheerleader_list %}
系統不支持用圓括號來組合比較操做。若是你發現須要組合操做,你能夠考慮用邏輯語句來簡化 模板的處理。例如,你須要組合 and 和 or 作些複雜邏輯判斷,可使用嵌套的 {% if %} 標籤,示例以下:less
{% if athlete_list %} {% if coach_list or cheerleader_list %} We have athletes, and either coaches or cheerleaders! {% endif %} {% endif %}
屢次使用同一個邏輯操做符是沒有問題的,可是咱們不能把不一樣的操做符組合起來。好比這樣的代碼是沒問題的:編程語言
{% if athlete_list or coach_list or parent_list or teacher_list %}
並無 {% elif %} 標籤,請使用嵌套的 {% if %} 標籤來達成一樣的效果:函數
{% if athlete_list %} <p>Here are the athletes: {{ athlete_list }}.</p> {% else %}
<p>No athletes are available.</p>
{% if coach_list %}
<p>Here are the coaches: {{ coach_list }}.</p>
{% endif %}
{% endif %}
必定要用 {% endif %} 關閉每個 {% if %} 標籤。不然Django會拋出 TemplateSyntaxError 。oop
2、for性能
{% for %} 容許咱們在一個序列上迭代。與Python的 for 語句的情形相似,循環語法是 for X in Y ,Y是要迭代的序列而X是在每個特定的循環中使用的變量名稱。每一次循環中,模板系統會渲染在 {% for %} and {% endfor %} 中的全部內容。
例如,給定一個運動員列表 athlete_list 變量,咱們可使用下面的代碼來顯示這個列表:
<ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% endfor %} </ul>
給標籤增長一個 reversed 使得該列表被反向迭代:
{% for athlete in athlete_list reversed %} ... {% endfor %}
能夠嵌套使用 {% for %} 標籤:
{% for country in countries %} <h1>{{ country.name }}</h1> <ul> {% for city in country.city_list %} <li>{{ city }}</li> {% endfor %} </ul> {% endfor %}
Django不支持退出循環操做。若是咱們想退出循環,能夠改變正在迭代的變量,讓其僅僅包含須要迭代的項目。同理,Django也不支持continue語句,咱們沒法讓當前迭代操做跳回到循環頭部。(請參看本章稍後的理念和限制小節,瞭解下決定這個設計的背後緣由){% for %} 標籤在循環中設置了一個特殊的 forloop 模板變量。這個變量能提供一些當前循環進展的信息:
forloop.counter 老是一個表示當前循環的執行次數的整數計數器。這個計數器是從1開始的,因此在第一次循環時 forloop.counter 將會被設置爲1。例子以下:
{% for item in todo_list %} <p>{{ forloop.counter }}: {{ item }}</p> {% endfor %}
forloop.counter0 相似於 forloop.counter ,可是它是從0計數的。第一次執行循環時這個變量會被設置爲0。
forloop.revcounter 是表示循環中剩餘項的整型變量。在循環初次執行時
forloop.revcounter 將被設置爲序列中項的總數。最後一次循環執行中,這個變量將被置1。
forloop.revcounter0 相似於 forloop.revcounter ,但它以0作爲結束索引。在第一次執行循環時,該變量會被置爲序列的項的個數減1。在最後一次迭代時,該變量爲0。
forloop.first 是一個布爾值。在第一次執行循環時該變量爲True,在下面的情形中這個變量是頗有用的。
{% for object in objects %} {% if forloop.first %}<li class="first">{% else %}<li>{% endif %} {{ object }} </li> {% endfor %}
forloop.last 是一個布爾值;在最後一次執行循環時被置爲True。一個常見的用法是在一系列的連接之間放置管道符(|)
{% for link in links %}{{ link }}{% if not forloop.last %} | {% endif %}{% endfor %} The above template code might output something like this:: Link1 | Link2 | Link3 | Link4
forloop.parentloop 是一個指向當前循環的上一級循環的 forloop 對象的引用(在嵌套循環的狀況下)。例子在此:
{% for country in countries %} <table> {% for city in country.city_list %} <tr> <td>Country #{{ forloop.parentloop.counter }}</td> <td>City #{{ forloop.counter }}</td> <td>{{ city }}</td> </tr> {% endfor %} </table> {% endfor %}
forloop 變量僅僅可以在循環中使用,在模板解析器碰到 {% endfor %} 標籤時, forloop 就不可訪問了。
Context和forloop變量
在一個 {% for %} 塊中,已存在的變量會被移除,以免 forloop 變量被覆蓋。Django會把這個變量移動到 forloop.parentloop 中。一般咱們不用擔憂這個問題,可是一旦咱們在模板中定義了 forloop 這個變量(固然咱們反對這樣作),在 {% for %} 塊中它會在 forloop.parentloop 被從新命名。
3、ifequal/ifnotequal
Django模板系統壓根兒就沒想過實現一個全功能的編程語言,因此它不容許咱們在模板中執行Python的語句(仍是那句話,要了解更多請參看理念和限制小節)。可是比較兩個變量的值而且顯示一些結果實在是個太常見的需求了,因此Django提供了 {% ifequal %} 標籤供咱們使用。
{% ifequal %} 標籤比較兩個值,當他們相同時,顯示在 {% ifequal %} 和 {% endifequal %} 之中全部的值。
下面的例子比較兩個模板變量 user 和 currentuser :
{% ifequal user currentuser %} <h1>Welcome!</h1> {% endifequal %}
參數能夠是硬編碼的字符串,隨便用單引號或者雙引號引發來,因此下列代碼都是正確的:
{% ifequal section 'sitenews' %} <h1>Site News</h1> {% endifequal %} {% ifequal section "community" %} <h1>Community</h1> {% endifequal %}
和 {% if %} 相似, {% ifequal %} 支持可選的 {% else%} 標籤:
{% ifequal section 'sitenews' %} <h1>Site News</h1> {% else %} <h1>No News Here</h1> {% endifequal %}
只有模板變量,字符串,整數和小數能夠做爲 {% ifequal %} 標籤的參數。這些是正確的例子:
{% ifequal variable 1 %} {% ifequal variable 1.23 %} {% ifequal variable 'foo' %} {% ifequal variable "foo" %}
其餘的一些類型,例如Python的字典類型、列表類型、布爾類型,不能用在 {% ifequal %} 中。 下面是些錯誤的例子:
{% ifequal variable True %} {% ifequal variable [1, 2, 3] %} {% ifequal variable {'key': 'value'} %}
若是你須要判斷變量是真仍是假,請使用 {% if %} 來替代 {% ifequal %} 。
4、註釋
象HTML和其餘的語言例如python同樣,Django模板系統也容許註釋。 註釋使用 {# #} :
{# This is a comment #}
註釋的內容不會在模板渲染時輸出。
註釋不能跨多行。這個限制是爲了提升模板解析的性能。在下面這個模板中,輸出結果和模板自己是 徹底同樣的(也就是說,註釋標籤並無被解析爲註釋):
This is a {# this is not
a comment #}
test.
5、其餘總結
(1)block 定義一個子模板能夠覆蓋的塊,在模板中(上一節)有使用示例
(2)comment 註釋,{% comment %} 和 {% endcomment %}之間的內容被解釋爲註釋
(3)crsf_token 一個防止CSRF攻擊(跨站點請求僞造)的標籤
(4)debug 輸出全部的調試信息,包括當前上下文和導入的模塊
(5)extends 表示說當前模板繼承了一個父模板 接受一個包含父模板名字的變量或者字符串常量
(6)load 加載一個自定義的模板標籤集合,見單獨的一節講解
(7)url 返回一個絕對路徑的引用(沒有域名的url),接受的第一個參數是一個視圖函數的名字,而後從urls配置文件裏面找到那個視圖函數對應的url,
(8)autoescape 控制當前自動轉義的行爲,有on和off兩個選項
{% autoescape on %}
{{ body }}
{% endautoescape %}
(9)cycle 循環給出的字符串或者變量,能夠混用
{% for o in some_list %} <tr class="{% cycle 'row1' rowvalue2 'row3' %}"> ... </tr> {% endfor %}
值得注意的是,這裏的變量的值默認不是自動轉義的,要麼你相信你的變量,要麼你就是用強制轉義的方法,
{% for o in some_list %} <tr class="{% filter force_escape %}{% cycle rowvalue1 rowvalue2 %}{% endfilter %}"> ... </tr> {% endfor %}
在某些狀況下,你可能想循環外部引用循環的下一個值,這時你須要用as給cycle標籤一個名字,這個名字表明的是當前循環的值,但你能夠在cycle標籤裏面是用這個變量來得到循環的下一個值。
<tr> <td class="{% cycle 'row1' 'row2' as rowcolors %}">...</td> <td class="{{ rowcolors }}">...</td> </tr> <tr> <td class="{% cycle rowcolors %}">...</td> <td class="{{ rowcolors }}">...</td> </tr>
渲染的結果是
<tr> <td class="row1">...</td> <td class="row1">...</td> </tr> <tr> <td class="row2">...</td> <td class="row2">...</td> </tr>
可是cycle標籤一旦定義,默認就會用循環的第一個值,當你僅僅是想定義一個循環,而不想打印循環的值的時候(好比你在父模板定義變量以方便繼承),你能夠是用cycle的silent參數(必須保證silent是cycle的最後一個參數,而且silent也具備繼承的特色,儘管第二行的cycle沒有silent參數,但因爲rowcoclors是前面定義的且包含silent參數的,第二個cycle也具備silent 循環的特色。
{% cycle 'row1' 'row2' as rowcolors silent %} {% cycle rowcolors %}
(10)filter 經過可用的過濾器過濾內容,過濾器之間還能夠相互(調用)
{% filter force_escape|lower %} This text will be HTML-escaped, and will appear in all lowercase. {% endfilter %}
(11)firstof 返回列表中第一個可用(非False)的變量或者字符串,注意的是firstof中的變量非自動轉義
{% firstof var1 var2 var3 "fallback value" %}
(12)for...empty 若是for循環的參數-列表爲空,將執行empty裏面的內容
<ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% empty %} <li>Sorry, no athlete in this list!</li> {% endfor %} <ul>
(13)ifchange
檢測一個值在循環的最後有沒有改變
因此這個標籤實在循環裏面是用的,有兩個用法:
沒有接受參數時,比較的是ifchange標籤裏面的內容相比之前是否有變化,有變化時生效
接受一個或以上各參數的時候,若是有一個或者以上的參數發生變化時,有變化時生效
ifchange能夠有else標籤
{% for match in matches %} <div style="background-color: {% ifchanged match.ballot_id %} {% cycle "red" "blue" %} {% else %} grey {% endifchanged %} ">{{ match }}</div> {% endfor %}
(14)ifequal 僅當兩個參數相等的時候輸出塊的內容,能夠配合else輸出
{% ifequal user.username "adrian" %} ... {% endifequal %}
(15)include
加載一個模板並用當前上下文(include該模板的模板的上下文)渲染它,接受一個變量或者字符串參數
固然你也能夠在include的時候傳遞一些參數進來
{% include "name_snippet.html" with person="Jane" greeting="Hello" %}
若是你只想接受傳遞的參數,不接受當前模板的上下文時,你能夠是用only參數
{% include "name_snippet.html" with greeting="Hi" only %}
(16)now 顯示當前的時間日期,接受格式化字符串的參數
It is {% now "jS F Y H:i" %}
參數有已經定義好的一些參考參數: DATE_FORMAT(月日年), DATETIME_FORMAT(月日年時),SHORT_DATE_FORMAT(月/日/年) or SHORT_DATETIME_FORMAT(月/日/年/時)
(17)spaceless 移除html標籤之間的空格,注意是標籤之間的空格,標籤與內容之間的空格不會被刪除
{% spaceless %} <p> <a href="foo/">Foo</a> </p> {% endspaceless %}
結果是
<p><a href="foo/">Foo</a></p>
(18)ssi 在頁面上輸出給定文件的內容
{% ssi /home/html/ljworld.com/includes/right_generic.html %}
使用parsed參數可使得輸入的內容能夠做爲一個模板從而可使用當前模板的上下文
{% ssi /home/html/ljworld.com/includes/right_generic.html parsed %}
(19)with 用更簡單的變量名緩存複雜的變量名
{% with total=business.employees.count %} {{ total }} employee{{ total|pluralize }} {% endwith %}
儘管初衷是這樣,但你沒必要都是如此,哈哈
{% with alpha=1 beta=2 %} ... {% endwith %}