- http://blog.chinaunix.net/uid-7429703-id-461731.html
- Summary
- 介绍
- 模版系统用法
- 语法
- 表达式替换
- 赋值
- 过滤
- Newline suppression
- 转义Escaping '$'
- 注释Comments
- 控制结构Control Structures
- 其他语句Other Statements
- $def : define a new template function using $def
- $code : arbitrary python code can be written
- $var : can be used to define additional properties
- Builtins and globals
- Security
- Upgrading from web.py 0.2 templates
介绍
- 设计 web.py 模版语言 Templetor 是想把 Python的强悍扩张到模版这块. 它重用了 python 语法,而不是重创一个. Templetor 限制从模版内访问变量.
- 下面是一个简单的模版:
- $def with (name)
- Hello $name!
- 首行在模版声明接受一个叫做 name 的参数. 渲染模版时第二行的 $name 将被替换成 name 的值.
- 使用模版系统
- 渲染模版最常用方式是:
- render = web.template.render('templates')
- print render.hello('world')
- 函数 render 接受一个模版库路径作为参数. render.hello(..) 使用给定的参数调用模版 hello.html. 实际上是在模版库下搜索首个匹配 hello.* 的文件.
- 当然,也可以用 frender 从指定文件创建模版.
- hello = web.template.frender('templates/hello.html')
- print hello('world')
- 当然,还可以将模版放到一个字符串中:
- template = "$def with (name)\nHello $name"
- hello = web.template.Template(template)
- print hello('world')
- 语法
- 表达式替换, 特殊字符 $ 用来指定 python 表达式.
- 表达式可以用 () 或 {} 括起来以显式区分.
- Look, a $string.
- Hark, an ${arbitrary + expression}.
- Gawk, a $dictionary[key].function('argument').
- Cool, a $(limit)ing.
- 赋值
- 有时需要定义新变量和重新赋值给某些变量.
- $ bug = get_bug(id)
- <h1>$bug.title</h1>
- <div>
- $bug.description
- <div>
- 注意赋值表达式中 $ 之后的空格.这里是必需的,以用来区别于表达式替换(如果没有空格: $bug = get(id), 则只是将 $bug 替换成值, 而不是赋值).
- 过滤
- Templetor默认采用 web.websafe 过滤器进行 HTML-编码.
- >>> render.hello("1 < 2")
- "Hello 1 < 2"
- 如果不需要过滤器,则在 '$' 后面加一个 ':', 就可以为其后(该行)的代码关闭暂时过滤器:
- 下面例子将不会被 html 转义.
- $:form.render()
- 续行
- 通过在行尾加反斜杠 \ 可以续行:
- If you put a backslash \
- at the end of a line \
- (like these) \
- then there will be no newline.
- 转义 '$'
- 用 $$ 可在输出中得到一个'$':
- Can you lend me $$50?
- 注释
- $# 用来表示注释. 该行其后所有内容都被忽略.
- $# this is a comment
- Hello $name.title()! $# display the name in title case
- 控制结构
- T模版系统支持 for, while, if, elif 和 else. 注意,和 python 一样, 控制体需要缩进.
- $for i in range(10):
- I like $i
- $for i in range(10): I like $i
- $while a:
- hello $a.pop()
- $if times > max:
- Stop! In the name of love.
- $else:
- Keep on, you can do it.
- 不同的是这里的 for 循环设置了循环中可以访问的一系列变量:
- loop.index: the iteration of the loop (1-indexed)
- loop.index0: the iteration of the loop (0-indexed)
- loop.first: True if first iteration
- loop.last: True if last iteration
- loop.odd: True if an odd iteration
- loop.even: True if an even iteration
- loop.parity: "odd" or "even" depending on which is true
- loop.parent: the loop above this in nested loops
- 有时,这是非常有用的.
- <table>
- $for c in ["a", "b", "c", "d"]:
- <tr class="$loop.parity">
- <td>$loop.index</td>
- <td>$c</td>
- </tr>
- </table>
- 其他语句
- def
- 使用 $def 可以定义新的模版函数. 同时还支持 Keyword arguments .
- $def say_hello(name='world'):
- Hello $name!
- $say_hello('web.py')
- $say_hello()
- Another example:
- $def tr(values):
- <tr>
- $for v in values:
- <td>$v</td>
- </tr>
- $def table(rows):
- <table>
- $for row in rows:
- $:row
- </table>
- $ data = [['a', 'b', 'c'], [1, 2, 3], [2, 4, 6], [3, 6, 9] ]
- $:table([tr(d) for d in data])
- code
- 在 code 块中可以写任意的 python 代码.
- $code:
- x = "you can write any python code here"
- y = x.title()
- z = len(x + y)
- def limit(s, width=10):
- """limits a string to the given width"""
- if len(s) >= width:
- return s[:width] + "..."
- else:
- return s
- 其中在 code 块中定义的变量就可以在之后使用了. 例如, $limit(x)
- var
- 在 var 块中用来定义模版结果中的其他属性.
- $def with (title, body)
- $var title: $title
- $var content_type: text/html
- <div id="body">
- $body
- </div>
- 上面模版的结果可以如下使用:
- >>> out = render.page('hello', 'hello world')
- >>> out.title
- u'hello'
- >>> out.content_type
- u'text/html'
- >>> str(out)
- '\n\n
\nhello world\n\n'
- builtins 和 globals
- Just like any Python function, template can also access builtins along with its arguments and local variables. Some common builtin functions like range, min, max etc. and boolean values True and False are made available to all the templates. Apart from the builtins, application specific globals can be specified to make them accessible in all the templates.
- Globals can be specified as an argument to web.template.render.
- import web
- import markdown
- globals = {'markdown': markdown.markdown}
- render = web.template.render('templates', globals=globals)
- Builtins that are exposed in the templates can be controlled too.
- # disable all builtins
- render = web.template.render('templates', builtins={})
- Security
- One of the design goals of Templetor is to allow untrusted users to write templates.
- To make the template execution safe, the following are not allowed in the templates.
- Unsafe statements like import, exec etc.
- Accessing attributes starting with _
- Unsafe builtins like open, getattr, setattr etc.
- SecurityException is raised if your template uses any of these.
- Upgrading from web.py 0.2 templates
- The new implementation is mostly compatible with the earlier implementation. However some cases might not work because of the following reasons.
- Template output is always storage like TemplateResult object, however converting it to unicode or str gives the result as unicode/string.
- Reassigning a global value will not work. The following will not work if x is a global.
- $ x = x + 1
- The following are still supported but not preferred.
- Using \$ for escaping dollar. Use $$ instead.
- Modifying web.template.Template.globals. pass globals to web.template.render as argument instead.