# Template

## Template

自動更新 app.config\['TEMPLATES\_AUTO\_RELOAD'] = True

## 動態變數

動態網頁操作上與django相似

```
# 單一變數
<h1>hello, {{ name }}! </h1>


# 迴圈
<ul>
    {% for comment in comments %}
        <li>{{ comment }}</li>
    {% endfor %}
</ul>
```

在flask中將變數傳送至template

```python
# python3
@app.route('/hihi',methods = ['post'])  
def test_function():  
    name = 'strawberry'
    comments = ['1', '2', '3']
    # 把所有變數加入render_template
    return render_template('signForm.html', name=name, comments=comments)
```

將html以變數方式傳送至template

```
# 可避免轉碼情況發生
{{ 變數名稱|safe }}
```

參考連結：\
<https://blog.csdn.net/lanchunhui/article/details/51570408>\
<https://blog.csdn.net/three_co/article/details/78420213>\
<https://stackoverflow.com/questions/3206344/passing-html-to-template-using-flask-jinja2>

## 判斷式

和在python使用方式差不多，可使用<>、and or not之類的

```
{% if kenny.sick %}
   Kenny is sick.
{% elif kenny.dead %}
   You killed Kenny!  You bastard!!!
{% else %}
   Kenny looks okay --- so far
{% endif %}
```

## 迴圈

遍歷字典

```
{% for key, value in my_dict.items() %}
    <dt>{{ key }}</dt>
    <dd>{{ value }}</dd>
{% endfor %}
```

可使用else，當遍歷的參數為空或None。無法使用continue和break

```
{% for user in users %}
    <li>{{ user.username }}</li>
{% else %}
    <li><em>no users found</em></li>
{% endfor %}
```

迴圈有些自帶的變數可以使用：

loop.index 循环迭代计数（从1开始）

loop.index0 循环迭代计数（从0开始）

loop.revindex 循环迭代倒序计数（从len开始，到1结束）

loop.revindex0 循环迭代倒序计数（从len－1开始，到0结束）

loop.first 是否为循环的第一个元素

loop.last 是否为循环的最后一个元素

loop.length 循环序列中元素的个数

loop.cycle 在给定的序列中轮循，如上例在”odd”和”even”两个值间轮循

loop.depth 当前循环在递归中的层级（从1开始）

loop.depth0 当前循环在递归中的层级（从0开始）

使用方式

```
{% for book in books %}
    <p>{{ loop.first }}</p>
    <p>{{ loop.index }}</p>
    <p>{{ book }}</p>
{% endfor %}
```

## Macro <a href="#hong-macro" id="hong-macro"></a>

類似在html使用function，方便又整齊，可以傳遞參數，但是不能有返回值

先定義input函式

```
{% macro input(name, value='', type='text') %}
    <input type="{{ type }}" name="{{ name }}" value="{{ value }}">
{% endmacro %}
```

使用時

```
<p>{{ input('username') }}</p>
<p>{{ input('password', type='password') }}</p>
```

## import

可將macro內容用.html儲存，其他html可用import方式讀取並使用macro

```
{% import 'macro.html' as macro  %}
<tr>
    <td>用戶名：</td>
    <td>{{ macro.input('username') }}</td>
</tr>
```

或者

```
{% from "macro.html" import input %}
<tr>
    <td>密碼：</td>
    <td>{{ input("password",type="password") }}</td>
</tr>
```

## include

將重複性高的html另外儲存，再用include讀取，就不用一直複製貼上相同的html惹

```
{% include 'header.html' %}
...
{% include 'footer.html' %}
```

## set

在html文件上宣告變數來使用

```
{% set name='dog' %}
{% set navigation = [('index.html', 'Index'), ('about.html', 'About')] %}
```

這樣就可以使用和惹

## with

可以用來限制set變數的效果範圍

```
{% with %}
    {% set foo = 42 %}
{% endwith %}
或者
{% with foo = 42 %}
    {{ foo }}
{% endwith %}
```

參考資料：

<https://www.twblogs.net/a/5e9d77f96052e105765a65b4>

{% embed url="<https://www.twblogs.net/a/5e9d77f96052e105765a65b7>" %}

{% embed url="<http://www.bjhee.com/jinja2-block-macro.html>" %}
