1、三種語法:
控制結構:{% %}
變量取值:{{ }}
註釋:{# #}
2、變量:
Jinja2識別所有的Python數據類型,包括列表、字典、對象等。
A value from a dictionary: {{ mydict['key'] }} A value from a list: {{ mylist[3] }} A value from a list, with a variable index: {{ mylist[myintvar] }} A value from an object's method: {{ myobj.method() }}
3、Jinja2中的過濾器:
過濾器名 | 說明 |
safe | 渲染值時不轉義 |
capitalize | 把值的首字母轉換成大寫,其他字母轉換成小寫 |
lower | 把值轉換成小寫 |
upper | 把值轉換成大寫 |
title | 把值中每個單詞的首字母轉換成大寫 |
trim | 把值的首尾空格去掉 |
striptags | 渲染之前把值中所有的HTML標籤刪掉 |
join | 拼接多個值爲字符串 |
replace | 替換字符串的值 |
round | 默認對數字進行四捨五入 |
int | 把值轉換爲整型 |
變量可以通過“過濾器”修改,過濾器與變量用管道(|)分隔。多個過濾器可以鏈式調用,前一個過濾器的輸出會作爲後一個過濾器的輸入。
{{ "Hello World" | replace("Hello", "Goodbye") }} -> Goodbye World {{ "Hello World" | replace("Hello", "Goodbye") | upper }} -> GOODBYE WORLD {{ 43.5 | round }} -> 44.0 {{ 43.5 | round | int }} -> 44
4、Jinja2的if條件:
{% if user %} Hello, {{ user }} {% else %} Hello, Stranger {% endif %}
5、Jinja2的for循環:
{% for comment in comments %} {{ comment }} {% endfor %}
6、Jinja2中的宏。類似於Python代碼中的函數:
{% macro render_comment(comment) %} {{ comment }} {% endmacro %} {% for comment in comments %} render_comment(comment) {% endfor %}
7、區分模版文件:
通過 - template: jinja 指令聲明一個sls文件是一個jinja模版文件。