Mako是什么?Moko是Python写的一个模板库,Python官网http://python.org/ 用的就是它哦。

(Mako官网地址:http://www.makotemplates.org/ ,可以下载安装包,推荐使用 easy_install 安装, 或者 通过 pip)

先来个简单的使用示例, 通过文本直接构建模板

from mako.template import Template
mytemplate = Template("hello world!")
print mytemplate.render()
mytemplate = Template("hello, ${name}!")
print mytemplate.render(name="jack")

通过文件构建模板

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

加载模板目录下的指定文件名作为模板

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

使用 TemplateLookup 缓存模板文件

from mako.lookup import TemplateLookup
mylookup = TemplateLookup(directories=['/docs'])
mytemplate = Template("""<%include file="header.txt"/> hello world!""", lookup=mylookup)

提供公共的入口, 方便使用统一的模板路径

mylookup = TemplateLookup(directories=['/docs'], module_directory='/tmp/mako_modules')
def serve_template(templatename, **kwargs):
    mytemplate = mylookup.get_template(templatename)
    print mytemplate.render(**kwargs)

定义模板的输入输出编码格式

mylookup = TemplateLookup(directories=['/docs'], 
    output_encoding='utf-8',
    encoding_errors='replace')
mytemplate = mylookup.get_template("foo.txt")
print mytemplate.render()

总体上 Mako Template 使用还是非常简便,有空写一篇对比 Jinja Mako 的文章, 对比下他们的使用异同.

【腾讯云】境外1核2G服务器低至2折,半价续费券限量免费领取!
https://cloud.tencent.com/act/cps/redirect?redirect=1068&cps_key=e4b50f6c64a4480367f8a8d16fd07c5a&from=console

标签: python, Moko, Template, TemplateLookup

添加新评论