一直使用Jinja2,前段时间听说mako,一试
大同小异,天下模板都差不多
要写代码测试,文档先行
资源
官网 http://www.makotemplates.org/
文档 http://docs.makotemplates.org/en/latest/
文档翻译 Mako模板入门 http://help.42qu.com/code/mako.html
安装
| 1 | pip install mako |
HelloWorld
| 123456789 | from mako.template import Template mytemplate = Template(\”hello world!\”)print mytemplate.render() ————————————– from mako.template import Templateprint Template(\”hello ${data}!\”).render(data=\”world\”) |
语法
| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 | 输出变量 ${x} 数学计算 ${1+1}the contents within the ${} tag are evaluated by Python directly, so full expressions are OK filter${\”test\”|u}${\”test\”|u,trim}内置filter列表 u : URL escaping, provided by urllib.quote_plus(string.encode(\’utf-8\’)) h : HTML escaping, provided by markupsafe.escape(string) x : XML escaping trim : whitespace trimming, provided by string.strip() entity : produces HTML entity references for applicable strings, derived from htmlentitydefs unicode (str on Python 3): produces a Python unicode string (this function is applied by default) decode. : decode input into a Python unicode with the specified encoding n : disable all default filtering; only filters specified in the local expression tag will be applied. 分支% if x == 5: abcd% endif 循环% for a in [\’1\’, \’2\’, \’3\’]: % if a == \’1\’: abc % elif a == \’2\’: def % else: gh % endif$ endfor Python语法this is a template x = db.get_resource(\’foo\’) y = [z.element for z in x if x.frobnizzle==5]%> % for elem in y: element: ${elem}% endfor 换行 加 / 强制不换行 |
注释
| 123456789 | ## 这是一个注释....text ... 多行%doc> 这里是注释更多注释/%doc> |
模块级别语句
的一个变体是 ,代表模块级别的代码块。其中的代码会在模板的模块级别执行,而不是在模板的 rendering 函数中。
| 1234567 | !import mylibimport re def filter(text): return re.sub(r\’^@\’, \’\’, text)%> |
标签
| 123456789101112131415161718192021222324252627282930313233343536373839404142 | 定义了当前模板的总体特性,包括缓存参数,以及模板被调用时期待的参数列表(非必须)page args=\”x, y, z=\’default\’\”/>page cached=\”True\” cache_type=\”memory\”/> include file=\”header.html\”/>hello worldinclude file=\”footer.html\”/> %def 标签用于定义包含一系列内容的一个 Python 函数,此函数在当前模板的其他某个地方被调用到 def name=\”myfunc(x)\”>this is myfunc, x is ${x}%def> ${myfunc(7)} block filter=\”h\”>some html> stuff.%block> block name=\”header\”> h2>block name=\”title\”/>h2>%block> Mako 中的 %namespace 等价于 Python 里的 import 语句。它允许访问其他模板文件的所有 rendering 函数和元数据namespace file=\”functions.html\” import=\”*\”/> inherit file=\”base.html\”/> 处理多行注释:doc> these are comments more comments%doc> 该标签使得 Mako 的词法器对模板指令的常规解析动作停止,并以纯文本的形式返回其整个内容部分text filter=\”h\”>heres some fake mako ${syntax}def name=\”x()\”>${x}%def>%text> |
有时你想中途停止执行一个模板或者 方法,只返回已经收集到的文本信息,可以通过在 Python 代码块中使用 return 语句来完成
| 12345 | % if not len(records): No records found. return %>% endif |
文件template
为提高性能,从文件中加载的 Template, 可以将它产生的模块的源代码以普通 python 模块文件的形式(.py),
缓存到文件系统中。只要加一个参数 module_directory 即可做到这一点:
| 1234 | from mako.template import Template mytemplate = Template |