您的位置:首页 > 编程语言 > Python开发

Python Mako笔记

2016-06-20 12:33 417 查看
译自 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
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: