python template mako 学习笔记

 Mako是什么?Moko是Python写的一个模板库,Python官网python.org 用的就是它哦。其他废话也就不累赘了,直接来点代码,方便阅读与了解把。

(Mako官网地址:http://www.makotemplates.org/ ,可以下载安装包,推荐使用easy_install安装)

from mako.template import Template
mytemplate
= Template ( "hello world!" )
print mytemplate . render ()

mytemplate = Template ( "hello, ${name}!" )
print mytemplate . render ( name = "jack" )

代码可以参考官方doc部分

mytemplate = Template ( filename = '/docs/mytmpl.txt' )
print mytemplate . render ()

还可以从设置模板为文件,设置filename 属性

mytemplate = Template ( filename = '/docs/mytmpl.txt' , module_directory = '/tmp/mako_modules' )
print mytemplate . render ()

文件还可以缓存到某个目录下,下面的/docs/mytmpl.txt会产生一个py: /tmp/mako_modules /docs/mytmpl.txt.py

from mako.lookup import TemplateLookup
mylookup = TemplateLookup ( directories = [ '/docs' ])
mytemplate = Template ( """< %i nclude file="header.txt"/> hello world!""" , lookup = mylookup )

查找模板,方便统一模板路径使用。

mylookup = TemplateLookup ( directories = [ '/docs' ], module_directory = '/tmp/mako_modules' )
def serve_template ( templatename , ** kwargs ):
     mytemplate = mylookup . get_template ( templatename )
     print mytemplate . render ( ** kwargs )

改良了上面的查找方式

mylookup = TemplateLookup ( directories = [ '/docs' ], output_encoding = 'utf-8' , encoding_errors = 'replace' )
mytemplate = mylookup . get_template ( "foo.txt" )
print mytemplate . render ()

设置输出编码,以及编码错误时候处理方式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值