提示及小技巧¶
說明文件中此部分顯示了 Jinja 範本的提示及小技巧。
Null 預設後備¶
Jinja 支援動態繼承,且不會區分父範本和子範本,只要未瀏覽 extends
標籤。儘管這會產生令人驚訝的行為,也就是 extends
標籤前的所有內容(包含空白)會印出,而非略過,但可用於一個小技巧。
通常子範本會從一個加入基本 HTML 架構的範本延伸。然而,可以將 extends
標籤放入 if
標籤中,以僅從佈局範本延伸,而僅當變數 standalone
評估為 false 時才會這麼做,當未定義 standalone
時變數預設會為 false。此外,會將非常基本的架構加入檔案,這樣一來,如果確實透過將 standalone
設為 True
來呈現,會加入非常基本的 HTML 架構。
{% if not standalone %}{% extends 'default.html' %}{% endif -%}
<!DOCTYPE html>
<title>{% block title %}The Page Title{% endblock %}</title>
<link rel="stylesheet" href="style.css" type="text/css">
{% block body %}
<p>This is the page body.</p>
{% endblock %}
交替列¶
如果您想針對表格或清單的每一列套用不同的樣式,可以使用 loop
物件上的 cycle
方法。
<ul>
{% for row in rows %}
<li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>
{% endfor %}
</ul>
cycle
可接受無限個字串。每當遇到此標籤時,就會呈現清單中的下一個項目。
存取以上的循環¶
特殊變數 loop
始終指向最內部的迴圈。如果想存取外部迴圈,可以使用別名存取
<table>
{% for row in table %}
<tr>
{% set rowloop = loop %}
{% for cell in row %}
<td id="cell-{{ rowloop.index }}-{{ loop.index }}">{{ cell }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>