2008年6月17日星期二

Web.py模板系统的tips [2008-6-12]

在webpy的模板系统里,仅能使用由程序传过来的变量和类,以及一些基本的itorator语句,不直接支持在模板里使用python的语句。如下面webpy的模板里的range和len会被系统报错,称“range”和“len”没有被定义。对于这种情况,有人说不好,不方便;也有人说就是应该这样,表现逻辑应该和呈现逻辑就是要区分开来,不应该允许在模板中直接调用python代码。
<h1>$title</h1>
$ for x in range(len(itemlist)):
<li> $x </li>

但是,如果以上例子能使用range和len将会带来很大的便利而并不会mix up所谓的表现逻辑和呈现逻辑。该怎么办?在webpy的论坛了,我找到了答案;)
只要在“表现逻辑”里增加以下语句,你的“呈现逻辑”模板就再也不会报错啦!
web.template.Template.globals['len'] = len
web.template.Template.globals['range'] = range


后来又找到一个更强的用法:

web.template.Template.globals['py'] = web.storify(__builtins__)

这样,你就可以使用py.xxx的方式,使用python所有的语句和函数啦!

2 条评论:

牛魔王 说...

现在webpy的templetor终于upgrade了,也可以说是re-written了一遍。
速度更快了,也增加了一些新的feature。我比较关心的是增加了一些常用的buildins,比如len啊,range之类的函数不必要再在主文件里export了。

The long awaited re-implementation of templator, the web.py templating
system, is now ready.

Whats new:

* It is fast: compiles the template to python code
* It is less space sensitive: the parser is completly re-written
* builtins are available in templates: builtins like range, min, max
etc are automatically made available to all templates
* More features: template functions, code blocks, django like loop.xxx vars.
* It is sandboxable as earlier: insecure code is not allowd inside templates
* Better unicode handling: output of the template is always unicode
* Better error reporting: the line causing the error is shown in the
exception traceback
* Easily extendable: more about this later

Checkout the complete documentation here:

http://webpy.org/docs/0.3/templetor

And code here:

bzr get http://webpy.org/bzr/webpy.dev

郎啊郎/阿郎/alang 说...

great!