butterfly_template

后端模板(butterfly 自带)

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'

Last updated