mako-基本使用
参考:
http://docs.makotemplates.org/en/latest/usage.html#basic-usage
Template
最常见创建模板方式,通过Template创建
from mako.template import Template
mytemplate = Template("hello world!")
print(mytemplate.render())
这个模块包含一个render_body()函数,该函数产生模板输出;
调用mytemplate.render()方法时,mako为该类建立运行环境,并调用render_body()方法;
然后捕获输出到buffer中,并在string中保存;
render_body()函数内的代码能够访问这个namespace中的变量,可以通过关键字传入;
from mako.template import Template
mytemplate = Template("hello, ${name}!")
print(mytemplate.render(name="jack"))
render方法创建一个Context对象,保存全部的变量名;并且保存一个用来保存输出的buffer,buffer可以自己创建或者用模板生成它;
使用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())
基于文件的模板
使用filename可以从文件中load
from mako.template import Template
mytemplate = Template(filename='/docs/mytmpl.txt')
print(mytemplate.render())
为了提高性能,mako可以配置一个已经渲染好的代码,下次使用的时候,直接返回这个结果
from mako.template import Template
mytemplate = Template(filename='/docs/mytmpl.txt', module_directory='/tmp/mako_modules')
print(mytemplate.render())
这样,会创建tmp/mako_modules/docs/mytmpl.txt.py文件
查找模板
使用TemplateLookup类
from mako.template import Template
from mako.lookup import TemplateLookup
mylookup = TemplateLookup(directories=['/docs'])
mytemplate = Template("""<%include file="header.txt"/> hello world!""", lookup=mylookup)
这样就会去/docs中查找header.txt
适当的使用get_template()方法,它接受期望模板的uri
from mako.template import Template
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))
这样,会从/docs中查找,把生成的模板放置到/tmp/mako_modules
get_template()调用的是最后生成的uri
设置Collection size
TemplateLookup能够做模板集合的缓冲
这个查找不断的把模板加载到内存,直到达到500的上限;然后清空不常用的;
mylookup = TemplateLookup(directories=['/docs'],
                module_directory='/tmp/mako_modules', collection_size=500)
filesystem_checks能够根据文件修改时间,更新模板,在生产环境关闭filesystem_checks能提高性能;
编码
可以使用output_encoding
from mako.template import Template
from mako.lookup import TemplateLookup
mylookup = TemplateLookup(directories=['/docs'], output_encoding='utf-8', encoding_errors='replace')
mytemplate = mylookup.get_template("foo.txt")
print(mytemplate.render())
render_unicode直接输出unicode形式
print(mytemplate.render_unicode())
可以自己编码
print(mytemplate.render_unicode().encode('utf-8', 'replace'))
异常处理
异常出现:
- lookup、parse、compile模板时
- 运行模板时
 text_error_template()
 html_error_template()
 两个函数用来格式化输出,都使用 sys.exc_info()输出
from mako import exceptions
try:
    template = lookup.get_template(uri)
    print(template.render())
except:
    print(exceptions.text_error_template().render()
from mako import exceptions
try:
    template = lookup.get_template(uri)
    print(template.render())
except:
    print(exceptions.html_error_template().render())
html_error_template()获取两个参数
指定full=False
指定css=False关闭默认的stylesheet渲染
例子
print(exceptions.html_error_template().render(full=False))
Template类中内置了render函数,使用format_exceptions标记,这时候获取的是html_error_template()
template = Template(filename="/foo/bar", format_exceptions=True)
print(template.render())
from mako.exceptions import RichTraceback
try:
    template = lookup.get_template(uri)
    print(template.render())
except:
    traceback = RichTraceback()
    for (filename, lineno, function, line) in traceback.traceback:
        print("File %s, line %s, in %s" % (filename, lineno, function))
        print(line, "\n")
    print("%s: %s" % (str(traceback.error.__class__.__name__), traceback.error))
 
                    
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号