--- tags: Python --- # Jinja2 [TOC] ## 名字由來 * 模板 template テンプレート * 神社 temple テンプル * 神社 じんじゃ 作者 Armin Ronacher 明明是澳洲人... > The name Jinja was chosen because it’s the name of a Japanese temple and temple and template share a similar pronunciation. ## Delimiter ### {% ... %} for **Statements** ### {{ ... }} for **Expressions** to print to the template output #### {# ... #} for **Comments** not included in the template output ## Live Parser * [Jinja live parser](https://cryptic-cliffs-32040.herokuapp.com/) ## Whitespace Control 官方文件:[Whitespace Control](http://jinja.pocoo.org/docs/2.10/templates/#whitespace-control) ### Delimiter 會佔行 ``` {% if true %} Paragraph {% endif %} ``` ```= Paragraph ``` ### 縮成一排 ``` {% if true %}Paragraph{% endif %} ``` ```= Paragraph ``` ### Flask Jinja Environment Variables ```python app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True ``` ### By hand > You can also strip whitespace in templates by hand. If you add a minus sign (-) to the start or end of a block (e.g. a For tag), a comment, or a variable expression, the whitespaces before or after that block will be removed. #### 吃裏 ``` --- {% if false -%} Paragraph {%- endif %} --- ``` ```= --- --- ``` #### 扒外 ``` --- {%- if false %} Paragraph {% endif -%} --- ``` ```= ------ ``` #### 吃裏又扒外 ``` {%- if false %} Paragraph {%- endif %} ``` ```= --- --- ``` #### 其他範例 ``` ••{% for item in range(1, 4) %}•• ••••{{ item }}• ••{% endfor %}•• ``` ```= •••• ∙∙∙∙1• •••• ••••2• •••• ••••3• •••• ``` ``` {% for item in range(1, 4) -%} {{ item }} {%- endfor %} ``` ```= ••123•• ``` ``` {%- for item in range(1, 4) %} {{ item }} {% endfor -%} ``` ```= •• ••••1• •••• ••••2• •••• ••••3• •• ``` ``` {%- for item in range(1, 4) %} {{ item }} {%- endfor %} ``` ```= •• ••••1•• ••••2•• ••••3•• ``` * 重要程度:Render 結果 > 排版美觀 ``` {%- for item in range(1, 4) %} {{item}} {% endfor %} ``` ```= •••1 •••2 •••3 ```