译自 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