使用文件系统模板时
from mako.template import Template
mytemplate = Template(filename='/docs/mytmpl.txt', module_directory='/tmp/mako_modules')
print(mytemplate.render())
传入module_directory时自动生成mytmpl.txt.py文件,下次使用同样参数时,这个模板自动被重用
templateLoopup
loopup将在指定目录中寻找文件,通常一个程序会把所有模板作为text files存放在文件系统中。
from mako.lookup import TemplateLookup
mylookup = TemplateLookup(directories=['/docs'], module_directory='/tmp/mako_modules')
def serve_template(templatename, **kwargs):
mytemplate = mylookup.get_template(templatename)
print(mytemplate.render(**kwargs))
上面的例子中,我们创建了TemplateLoopup在/docs目录中寻找,并在/tmp目录中储存了模板文件。
Lookup通过给每个搜索目录尾部附加指定URI的方式定位模板。
举例如果你指定URI:/etc/beans/info.txt,他就会去寻找/docs/etc/beans/info.txt,否则就报错
TopLevelNotFound,这个错误十分常见。
lookup定位到模板以后,它就分配一个URI属性给Template,过程是URI通过调用get_templates()方法。
Template用这个URI计算出它的模板文件,在上面的例子中,变量templatename:'/etc/beans/info.txt'会创建模
板文件/tmp/mako_modules/etc/beans/info.txt.py
Template()参数中还可设定collection_size=500,它默认为unbounded无限制,是内存缓冲大小。
还可设定filesystem_checks,默认为True,每次get_template方法调用返回一个template的时候检查源模板是否
改变,若改变了就重新载入并编译。
还可设定output_encoding='utf-8',设置编码格式。
常用框架整合
WSGI:独立的服务器提供GET,POST响应要求进入mako.runtime.Context,提供图片,CSS和其他文件的服务,使用
mako内置错误处理工具展示错误。
PYGMENTS:内置在mako.ext.pygmentplugin,用于生成文档,在也包含各种setuptools entry,包括
mako,html+mako,xml+mako
BABEL:MAKO提供从经过BABEL提取器从templates提取gettext消息的功能,它在mako.ext.babelplugin中
from mako.template import Template
mytemplate = Template(filename='/docs/mytmpl.txt', module_directory='/tmp/mako_modules')
print(mytemplate.render())
传入module_directory时自动生成mytmpl.txt.py文件,下次使用同样参数时,这个模板自动被重用
templateLoopup
from mako.template import Template
mylookup = TemplateLookup(directories=['/docs'])
loopup将在指定目录中寻找文件,通常一个程序会把所有模板作为text files存放在文件系统中。
实际的程序基本上都是从TemplateLookup中得到,使用名似"get_template"的方法,它接受指定模板的URI
from mako.lookup import TemplateLookup
mylookup = TemplateLookup(directories=['/docs'], module_directory='/tmp/mako_modules')
def serve_template(templatename, **kwargs):
mytemplate = mylookup.get_template(templatename)
print(mytemplate.render(**kwargs))
上面的例子中,我们创建了TemplateLoopup在/docs目录中寻找,并在/tmp目录中储存了模板文件。
Lookup通过给每个搜索目录尾部附加指定URI的方式定位模板。
举例如果你指定URI:/etc/beans/info.txt,他就会去寻找/docs/etc/beans/info.txt,否则就报错
TopLevelNotFound,这个错误十分常见。
lookup定位到模板以后,它就分配一个URI属性给Template,过程是URI通过调用get_templates()方法。
Template用这个URI计算出它的模板文件,在上面的例子中,变量templatename:'/etc/beans/info.txt'会创建模
板文件/tmp/mako_modules/etc/beans/info.txt.py
Template()参数中还可设定collection_size=500,它默认为unbounded无限制,是内存缓冲大小。
还可设定filesystem_checks,默认为True,每次get_template方法调用返回一个template的时候检查源模板是否
改变,若改变了就重新载入并编译。
还可设定output_encoding='utf-8',设置编码格式。
常用框架整合
WSGI:独立的服务器提供GET,POST响应要求进入mako.runtime.Context,提供图片,CSS和其他文件的服务,使用
mako内置错误处理工具展示错误。
PYGMENTS:内置在mako.ext.pygmentplugin,用于生成文档,在也包含各种setuptools entry,包括
mako,html+mako,xml+mako
BABEL:MAKO提供从经过BABEL提取器从templates提取gettext消息的功能,它在mako.ext.babelplugin中