# butterfly\_template

## 1 模板语法

### 1.1 数据替换

双大括号内包含 Python 表达式，并且可以通过管道符"|"处理生成的文本

```
<p>Short name: {{story.subject|slugify|lower}}</p>
```

### 1.2 控制流语句

> if

```
{% if user.is_logged_in %}
    <p>Welcome, {{ user.name }}!</p>
{% endif %}
```

> for

```
<ul>
{% for product in product_list %}
    <li>{{ product.name }}: {{ product.price|format_price }}</li>
{% endfor %}
</ul>
```

### 1.3 注释

```
{# This is the best template ever! #}
```

## 2 渲染前端

### 2.1 模板文本

> 一般放在 \<butterfly\_project>/templates 下

```
<p>Welcome, {{user_name}}!</p>
<p>Products:</p>
<ul>
{% for product in product_list %}
    <li>{{ product.name }}:
        {{ product.price|format_price }}</li>
{% endfor %}
</ul>
```

> * 文本
> * 注释：{# ... #}
> * 数据替换：{{ ... }}，如：{{user\_name}}，{{product.name}}
> * 控制结构：{% ... %}

### 2.2 渲染模板

```
from collections import namedtuple

from xlib import template

def  demo(req):
    with open("./templates/host_unit.tpl", "r") as f:
        template_text = f.read()

    Product = namedtuple("Product",["name", "price"])
    product_list = [Product("Apple", 1), Product("Fig", 1.5), Product("Pomegranate", 3.25)]

    def format_price(price):
        return "$%.2f" % price

    # 解析模板
    t = template.Templite(template_text, {"user_name":"Charlie", "product_list":product_list}, {"format_price":format_price})
    # 渲染模板
    print t.render()

if __name__ == "__main__":
    demo()
```

## 3 常见问题

### 3.1 模板中的 key 没有被渲染

此时会抛出异常

```
Traceback (most recent call last):
  ...
  File "<string>", line 2, in render_function
KeyError: 'xxx'
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://meetbill.gitbook.io/butterfly-user-doc/fe/butterfly_template.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
