官方地址:
https://github.com/defunkt/pystache
pystache是小胡子(mustache)的python版本插件。它的特点是轻量级、使用简单。
pystache支持变量替换、列表遍历、条件判断等。更多的使用方法见官方文档。
小例子:
# -*- coding=utf-8 -*-
'''
Created on 2013-3-11
@author: lingjun.gong(jialan)
'''
import pystache
c = {
"header": "Colors",
"items": [
{"name": "red", "first": True, "url": "#Red"},
{"name": "green", "link": True, "url": "#Green"},
{"name": "blue", "link": True, "url": "#Blue"}
],
"empty": False
}
c2 = {
"header": "Colors2222",
"items": [
{"name": "red2222", "first": True, "url": "#Red"},
{"name": "green2222", "link": True, "url": "#Green"},
{"name": "blue2222", "link": True, "url": "#Blue"}
],
"empty": False
}
r=pystache.Renderer()
filecontent= r.render_name("ttt",c) #使用render_name会自动寻找当前文件夹中的 ttt.mustache 文件作为模板
print filecontent
t = open("ttt.mustache", "r") #用文件作为模板
filecontent=pystache.render(t.read(), c2)
print filecontent
print 'DONE!'
模板 ttt.mustache:
<h1>{{header}}</h1>
{{#bug}}
{{/bug}}
{{#items}}
{{#first}}
<li><strong>{{name}}</strong></li>
{{/first}}
{{#link}}
<li><a href="{{url}}">{{name}}</a></li>
{{/link}}
{{/items}}
{{#empty}}
<p>The list is empty.</p>
{{/empty}}