代码改变世界

Python模板库Mako的用法

2015-05-07 16:35  折翼的鸟  阅读(4650)  评论(0编辑  收藏  举报

官网地址:http://www.makotemplates.org/

文档地址:http://docs.makotemplates.org/

中文文档基本用法地址:http://www.open-open.com/lib/view/open1405317963680.html

 

介绍:

Mako是一个高性能的Python模板库,Python官网python.org用的就是它

 

简单用法

from mako.template import Template
print(Template("hello ${data}!").render(data="world"))

使用文件模板

# -*- coding: utf-8 -*-
from mako.template import Template
from mako.lookup import TemplateLookup
html_path = '/Users/Dream/oe_dev/openerp/addons/lezyo_install/static/account'
lookup = TemplateLookup(
    directories=[html_path],
    output_encoding='utf-8', 
    input_encoding='utf-8',
    default_filters=['decode.utf8'],
    encoding_errors='replace'
)
some_template = lookup.get_template("/a.html")
values = {
    'reference': 'ss',
}
print some_template.render(**values)
 
# html 文件里面变量统一用:${reference}格式

  

注: 

mako 出现 raise NameError(“Undefined”) NameError: Undefined

就是html里用到了变量,但是你render()没有传递给他。

奇怪的是html 里即使你注释掉了变量,mako也会查到的…