web.py Templetor

来源:互联网 发布:发烧碟推荐知乎 编辑:程序博客网 时间:2024/06/05 11:02
  1. http://blog.chinaunix.net/uid-7429703-id-461731.html
  2. Summary
  3. 介绍
  4. 模版系统用法
  5. 语法
  6. 表达式替换
  7. 赋值
  8. 过滤
  9. Newline suppression
  10. 转义Escaping '$'
  11. 注释Comments
  12. 控制结构Control Structures
  13. 其他语句Other Statements
  14. $def : define a new template function using $def
  15. $code : arbitrary python code can be written
  16. $var : can be used to define additional properties
  17. Builtins and globals
  18. Security
  19. Upgrading from web.py 0.2 templates

介绍
  1. 设计 web.py 模版语言 Templetor 是想把 Python的强悍扩张到模版这块. 它重用了 python 语法,而不是重创一个. Templetor 限制从模版内访问变量.

  2. 下面是一个简单的模版:

  3. $def with (name)
  4. Hello $name!

  5. 首行在模版声明接受一个叫做 name 的参数. 渲染模版时第二行的 $name 将被替换成 name 的值.


  6. 使用模版系统
  7. 渲染模版最常用方式是:

  8. render = web.template.render('templates')
  9. print render.hello('world')

  10. 函数 render 接受一个模版库路径作为参数. render.hello(..) 使用给定的参数调用模版 hello.html. 实际上是在模版库下搜索首个匹配 hello.* 的文件.

  11. 当然,也可以用 frender 从指定文件创建模版.

  12. hello = web.template.frender('templates/hello.html')
  13. print hello('world')

  14. 当然,还可以将模版放到一个字符串中:

  15. template = "$def with (name)\nHello $name"
  16. hello = web.template.Template(template)
  17. print hello('world')



  18. 语法

  19. 表达式替换, 特殊字符 $ 用来指定 python 表达式. 
  20. 表达式可以用 ()  {} 括起来以显式区分.

  21. Look, a $string.
  22. Hark, an ${arbitrary+ expression}.
  23. Gawk, a $dictionary[key].function('argument').
  24. Cool, a $(limit)ing.


  25. 赋值
  26. 有时需要定义新变量和重新赋值给某些变量.

  27. $ bug = get_bug(id)
  28. <h1>$bug.title</h1>
  29. <div>
  30.     $bug.description
  31. <div>

  32. 注意赋值表达式中 $ 之后的空格.这里是必需的,以用来区别于表达式替换(如果没有空格: $bug = get(id), 则只是将 $bug 替换成值, 而不是赋值).


  33. 过滤
  34. Templetor默认采用 web.websafe 过滤器进行 HTML-编码.

  35. >>> render.hello("1 < 2")
  36. "Hello 1 &lt; 2"

  37. 如果不需要过滤器,则在 '$' 后面加一个 ':', 就可以为其后(该行)的代码关闭暂时过滤器:

  38. 下面例子将不会被 html 转义.
  39. $:form.render()

  40. 续行
  41. 通过在行尾加反斜杠 \ 可以续行

  42. If you put a backslash \
  43. at the end of a line \
  44. (like these) \
  45. then there will be no newline.

  46. 转义 '$'
  47. 用 $$ 可在输出中得到一个'$':
  48. Can you lend me $$50?

  49. 注释
  50. $# 用来表示注释. 该行其后所有内容都被忽略.
  51.          $# this is a comment   
  52. Hello $name.title()! $# display thename in title case


  53. 控制结构
  54. T模版系统支持 for, while, if, elif else. 注意,和 python 一样, 控制体需要缩进.

  55. $for i in range(10):
  56.     I like $i

  57. $for i in range(10):I like $i

  58. $while a:
  59.     hello $a.pop()

  60. $if times > max:
  61.     Stop! In the name of love.
  62. $else:
  63.     Keep on, you can do it.

  64. 不同的是这里的 for 循环设置了循环中可以访问的一系列变量:
    1. loop.index: the iteration of the loop (1-indexed)
    2. loop.index0: the iteration of the loop (0-indexed)
    3. loop.first: True if first iteration
    4. loop.last: True if last iteration
    5. loop.odd: True if an odd iteration
    6. loop.even: True if an even iteration
    7. loop.parity: "odd"or "even" depending on which is true
    8. loop.parent: the loop above this in nested loops

    9. 有时,这是非常有用的.
  65. <table>
  66. $for c in ["a","b", "c", "d"]:
  67.     <trclass="$loop.parity">
  68.         <td>$loop.index</td>
  69.         <td>$c</td>
  70.     </tr>
  71. </table>


  1. 其他语句
  2. def
  3. 使用 $def 可以定义新的模版函数. 同时还支持 Keyword arguments.

  4. $def say_hello(name='world'):
  5.     Hello $name!

  6. $say_hello('web.py')
  7. $say_hello()
  8. Another example:

  9. $def tr(values):
  10.     <tr>
  11.     $for v in values:
  12.         <td>$v</td>
  13.     </tr>

  14. $def table(rows):
  15.     <table>
  16.     $for row in rows:
  17.         $:row
  18.     </table>

  19. $ data =[['a','b', 'c'],[1, 2, 3],[2, 4, 6],[3, 6, 9]]
  20. $:table([tr(d)for d in data])




  1. code
  2. 在 code 块中可以写任意的 python 代码.

  3. $code:
  4.     x = "you can write any python code here"
  5.     y = x.title()
  6.     z = len(x+ y)

  7.     def limit(s,width=10):
  8.         """limits a string to the given width"""
  9.         if len(s)>= width:
  10.             return s[:width]+ "..."
  11.         else:
  12.             return s
  13. 其中在 code 块中定义的变量就可以在之后使用了. 例如, $limit(x)


  14. var
  15. var 块中用来定义模版结果中的其他属性.

  16. $def with (title,body)

  17. $var title: $title
  18. $var content_type: text/html

  19. <div id="body">
  20. $body
  21. </div>
  22. 上面模版的结果可以如下使用:

  23. >>> out= render.page('hello','hello world')
  24. >>> out.title
  25. u'hello'
  26. >>> out.content_type
  27. u'text/html'
  28. >>> str(out)
  29. '\n\n
    \nhello world\n
    \n'



  1. builtins  globals

  2. Just like any Python function, template can also access builtins along with its argumentsand 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.

  3. Globals can be specified as an argument to web.template.render.

  4. import web
  5. import markdown

  6. globals = {'markdown': markdown.markdown}
  7. render = web.template.render('templates', globals=globals)
  8. Builtins that are exposed in the templates can be controlled too.

  9. # disable all builtins
  10. render = web.template.render('templates', builtins={})

  11. Security

  12. One of the design goals of Templetor is to allow untrusted users to write templates.
  13. To make the template execution safe, the following arenot allowed in the templates.

  14. Unsafe statements like import, exec etc.
  15. Accessing attributes starting with _
  16. Unsafe builtins like open, getattr, setattr etc.
  17. SecurityException is raised if your template uses any of these.


  18. Upgrading from web.py 0.2 templates

  19. The new implementation is mostly compatible with the earlier implementation. However some cases mightnot work because of the following reasons.

  20. Template output is always storage like TemplateResult object, however converting it to unicodeor str gives the result as unicode/string.
  21. Reassigning a global value will not work. The following willnot work if x is a global.

  22.   $ x = x + 1
  23. The following are still supported but not preferred.

  24. Using \$ for escaping dollar. Use $$ instead.
  25. Modifying web.template.Template.globals. pass globals to web.template.render as argument instead.
原创粉丝点击