代码改变世界

mako模板系统(一)

2012-07-27 11:56  ubunoon  阅读(5169)  评论(0编辑  收藏  举报

python中的模板系统比较多,我比较喜欢用的是mako。

 

mako模板的功能

 

变量取代:

 

${}

 

在里面可以执行python内建的函数,以及通过模板Context传递过来的变量取代,受jsp等影响。

 

过滤器(文档说是 Expression Escaping-表达式转义)

 

在变量取代中 | 来表示过滤,内建 u-URL escaping, h-HTML escaping, x-XML escaping,以及trim四个过滤器。

 

结构控制


有if/else/elif, while/for, try/except,用%开头,用%end<name>结尾,name为表达式名称,与python一样,需要尾部添加:来表示一个表达式开始,但缩进不是必须的。

由于%被特殊使用,所有想要表达%,得用%%

 

注释

 

和其他语言一样,有单行和多行注释,单行用##,多行用<%doc></%doc>

 

换行过滤器

 

\在一行的结尾,表示下一行也是这一行的内容,连接上下两行内容为一行内容。

 

here is a line that goes onto \
another line.

等价:
here is a line that goes onto another line.

 

Python块

mako支持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

 

 上面的一个变形是模块级别的支持,用<%!开始

 

<%!
    import mylib
    import re

    def filter(text):
        return re.sub(r'^@', '', text)
%>

注意,此处需要纯的python代码

 


标签

类似XML,用%开头,用/结束或者显示的结束标签

 

<%include file="foo.txt" />

<%def name="foo" buffered="True">

  this is a def

</%def>

 

所有的tag有各自的属性,大部分属性支持evaluation,这表示你可以在属性文本中使用${}

<%include file="/foo/bar/${myfile}.txt" />

 

下面为所有tag

 

<%page>

  每个模板中仅能使用一个<%page>标签,剩下的会被忽略。

 

<%include>

  包含一个文件,然后将文件render出来,include可以包含参数

<%include file="toolbar.html" args="current_section='members', username='ed" />

 

<%def>

      定义一个python函数,可以被其他的模板调用

  <%def name="myfunc(x)">

    this is myfunc, x is ${x}

  </%def>

 

<%block>

  类似%def,可以匿名,从Jinja2中的block中引用过来

 

<%namespace>

  等价于python的import语句,可以用来render函数以及模板文件源数据,python模块等。

 

<%inherit>

  允许模板构成继承链,当构成inherit时,控制首先运行inherit部分模板。

 

<%nsname:defname>

  任何用户定义的名字,类似于<%call>的行内调用

 

<%call>

  比上面的<%nsname:defname>要复杂

 

<%doc>

  多行注释

 

<%text>

  挂起mako语法分析,返回整个文本,通常用来编写文档时使用

 

 

从模板中快速返回

    有时候想要停止处理模板或者<%def>,在python的block中使用return语句。

 

%if not len(records):

     no records found.

  <% return %>

%endif

<%

  if not len(records):

    return

%>