<p>Short name: {{story.subject|slugify|lower}}</p>
{% if user.is_logged_in %}
<p>Welcome, {{ user.name }}!</p>
{% endif %}
<ul>
{% for product in product_list %}
<li>{{ product.name }}: {{ product.price|format_price }}</li>
{% endfor %}
</ul>
{# This is the best template ever! #}
一般放在 <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>
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()
Traceback (most recent call last):
...
File "<string>", line 2, in render_function
KeyError: 'xxx'