免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 11825 | 回复: 4
打印 上一主题 下一主题

Python模板Mako学习笔记 <一> [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-05-27 10:08 |只看该作者 |倒序浏览
原文:http://hi.baidu.com/smallfish_xy/blog/item/8e1fc288980ec7bb0e24445f.html

Mako是什么?Moko是Python写的一个模板库,Python官网python.org用的就是它哦。其他废话也就不累赘了,直接来点代码,方便阅读与了解把。

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

from mako.template import Template
mytemplate = Template("hello world!")
print mytemplate.render()

mytemplate = Template("hello, ${name}!")
print mytemplate.render(name="jack")

代码可以参考官方doc部分

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

还可以从设置模板为文件,设置filename属性

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

文件还可以缓存到某个目录下,下面的/docs/mytmpl.txt会产生一个py:/tmp/mako_modules/docs/mytmpl.txt.py

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()

设置输出编码,以及编码错误时候处理方式

论坛徽章:
0
2 [报告]
发表于 2009-05-30 13:10 |只看该作者
正学习中

论坛徽章:
0
3 [报告]
发表于 2009-05-30 13:14 |只看该作者
不错,学习

论坛徽章:
0
4 [报告]
发表于 2009-05-30 14:50 |只看该作者
mako有一点不好,cache没留接口,强制用了beaker.cache,结果又会扯一大堆thread之类的进去,本身wsgi用stackless,greetlet处理的比较麻烦

论坛徽章:
0
5 [报告]
发表于 2009-05-31 08:08 |只看该作者
原帖由 3227049 于 2009-5-30 14:50 发表
mako有一点不好,cache没留接口,强制用了beaker.cache,结果又会扯一大堆thread之类的进去,本身wsgi用stackless,greetlet处理的比较麻烦

有空瞅瞅
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP