Jinja2
| 原作者 | Armin Ronacher |
|---|---|
| 首次發布 | 2008年7月17日[1] |
| 當前版本 |
|
| 原始碼庫 | |
| 程式語言 | Python |
| 類型 | 模板引擎 |
| 許可協議 | BSD許可證 |
| 網站 | palletsprojects |
Jinja2是為Python提供的一個功能齊全的模板引擎。Jinja2提供了對Unicode的完全支持,以及一個可選的集成沙盒運行環境。它使用BSD許可證。
Jinja模板引擎允許對標籤[3]、過濾器(用來格式化或變換值[4])、測試(用來評估條件[4])和全局變量[5]。不像Django模板引擎,Jinja允許模板設計者在對象上調用具有參數的函數。Jinja是Flask還有Home Assistant自動化的缺省模板引擎[6][7]。它還被用於Ansible[8]、Trac和Salt[9]。它也用於製作SQL宏,例如dbt[10]。
主要特徵:
[編輯]Jinja就像Smarty,還備有類似Unix管道的易用的過濾系統。
語法
[編輯]打印輸出的語法使用雙花括號,例如{{ Hello, World! }}。
設置變量的語句或沒有輸出的語句可以包裝在{% and %}之中,例如{% set foo = 42 %},這裏使用了set關鍵字,它設置叫做foo的變量具有值42。
註釋可以可以包裝在{# and #}之中,例如{# helpful comment #}。
建立過濾器的語法是豎線(|),例如{{ variable|filter }}。一個變量可以有多個過濾器,例如{{ variable|filter|filter }}[4]。
建立測試的語法是關鍵字is,以及評估一個測試有效性的條件,例如{% if variable is divisibleby 10 %}do something{% endif %}[4]。
可以使用For循環來迭代於序列之上,同時保持它們的對象屬性。下面的例子展示迭代於一個列表users之上,它具有username和password字段。
{% for user in users %}
{{ user.username }}
{{ user.password }}
{% endfor %}
儘管break和continue不允許出現在循環中,序列是可以過濾的。
例子
[編輯]下面的小例子是一個模板文件example.html.jinja[11]:
<!DOCTYPE html>
<html>
<head>
<title>{{ variable|escape }}</title>
</head>
<body>
{% for item in item_list -%}
{{ item }}{% if not loop.last %}, {% endif %}
{%- endfor %}
</body>
</html>
和一個模板代碼:
from jinja2 import Template
with open("example.html.jinja") as f:
tmpl = Template(f.read())
print(tmpl.render(
variable = "Value with <unsafe> data",
item_list = [1, 2, 3, 4, 5, 6]
))
它產生HTML字符串:
<!DOCTYPE html>
<html>
<head>
<title>Value with <unsafe> data</title>
</head>
<body>
1, 2, 3, 4, 5, 6
</body>
</html>
注意如果向一個塊(比如這裏的for標籤)、註釋或變量表達式的開頭或結尾增加一個減號(-),則在這個塊前面或後面的空白都會刪除[12]。
引用
[編輯]- ^ Jinja2 Release History. [24 June 2020]. (原始內容存檔於2018-10-03).
- ^ Release 3.1.6. 2025年3月5日 [2025年3月25日].
- ^ Extensions. Jinja2 Documentation (2.8-dev). [2015-05-26].
- ^ 4.0 4.1 4.2 4.3 Jinja built-in filters and tests.
- ^ Extensions. Jinja2 Documentation (2.8-dev). [2015-05-26].
- ^ DuPlain, R. Instant Flask Web Development. Packt Publishing. 2013: 30 [2015-05-26]. ISBN 978-1-78216-963-5.
- ^ Assistant, Home. Templating. Home Assistant. [2025-10-16] (英語).
- ^ Templating (Jinja2) — Ansible Documentation.
- ^ Understanding Jinja. docs.saltproject.io.
- ^ Jinja and macros | dbt Developer Hub
- ^ Ronacher, Armin. Template Designer Documentation. Jinja Documentation (3.0.x). [9 January 2024].
A Jinja template doesn’t need to have a specific extension: .html, .xml, or any other extension is just fine.
- ^ Template Designer Documentation — Jinja Documentation (3.0.x). jinja.palletsprojects.com. [2024-01-09].