Python Mako笔记

译自 http://docs.makotemplates.org/en/latest/usage.html#basic-usage


BasicUsage

        最基本的是用Template

from mako.template import Template

mytemplate = Template("hello world!")
print(mytemplate.render())

        以上,文本参数被编译为一个python模块对象。这个模块有个render_body()函数,产生模板的输出。当调用mytemplate_render()函数,Mako为模板建立一个运行环境并且调用render_body()函数,将输出存入缓存并返回字符串内容。

        render_body()内的函数有一些变量的命名空间,你可以通过传递参数指定这些变量。

from mako.template import Template

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

        render()方法调用Mako创建Context对象,其中存储模板中变量的名字并且有存放输出的缓存。你可以自己创建Context对象,用render_context()方法。

from mako.template import Template
from mako.runtime import Context
from StringIO import StringIO

mytemplate = Template("hello, ${name}!")
buf
= StringIO()
ctx
= Context(buf, name="jack")
mytemplate
.render_context(ctx)
print(buf.getvalue())

 

UsingFile-Based Templates

        也可以从文件中获取模板,用filename参数。

from mako.template import Template

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

        为了改进性能,从文件载入的模板也可以缓存为python模块,只需要增加module_directory参数。

from mako.template import Template

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

        下次创建相同参数的模板时,就会自动重用这个模块文件。

 

UsingTemplateLookup

 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值