web.py模版系统

介绍:

调用的web.py模版语言Templetor旨在将python的强大功能带入模版。它不是为模板创建新语法,而是重用python语法。

Templetor故意限制模版中的变量访问。用户可以访问传递给模版的变量和一些内置的python函数,这允许不受信任的用户编写模版,而不用担心他们会对正在运行的系统造成损害,当然,可以增加可用的全局变量。

简单的模版:

$def with (name)
Hello $name!

第一行表示定义了一个名为name的参数,$name在渲染模版时,第二行中的名称将替换为name的值。

使用模版系统: 

渲染模版的常用方法是:

render = web.template.render('templates')


return render.hello('world')

该render函数将模版root作为参数。使用给定的参数render.hello(..)调用模版hello.html。实际上,它会hello.* 在模版根目录中查找匹配的文件并选择第一个匹配文件。

也可以使用文件从文件创建模版render.

hello = web.template.frender('templates/hello.html')

print hello('world')

如果将模版作为字符串:

template = "$def with (name)
Hello $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>

注意$分配后的空格,需要区分赋值和表达式替换。、、

过滤: 

默认情况下,Templetor使用web.websafe过滤器进行HTML编码。

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

要使用:后关闭过滤器$:

The following will not be html escaped.
$: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?

$#用作评论指标,任何一$#开头直至行尾的内容都会被忽略。 

控制结构: 

模版系统支持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 say_hello(name='world'):
    Hello $name!

$say_hello('web.py')
$say_hello()

例子:

$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块写入任意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) >= 
            return s[:width] + "..."
        else:
            return s
            
And we are back to template.
The variables defined in the code block can be used here.
For example, $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)
'

<div>
hello world
</div>
'

内置和全局:

就像任何python函数一样,模版也可以访问内置函数及其参数和局部变量。像一些常见的内置函数,range, min,max等,以及布尔值True和False被提供给所有的模版,除了内置函数之外,还可以指定特定于应用程序的全局变量,以使他们可以在所有的模版中访问。

可以将Globals指定为参数web.template.render.

import web
import markdown

globals = {'markdown': markdown.markdown}
render = web.template.render('templates', globals=globals)

也可以控制在模版中公开的内置组件。

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

安全:

Templetor的设计目标之一是允许不受信任的用户编写模版。

要是模版执行安全,模版中不允许以下内容:

  • 不安全之类的语句import , exec 等等
  • 访问以 。开头的属性_
  • 不安全内建想open,getattr,setattr等等。

SecurityException 如果您的模板使用其中任何一个,则会引发

从web.py 0.2模版升级:

新实现大多与早期实现兼容。但是,由于以下原因,某些情况可能无效。

  • 模板输出始终像TemplateResult对象一样存储,但是将其转换为unicode或者str将结果作为unicode / string。
  • 重新分配全球价值将无效。如果x是全局的,则以下内容不起作用。

  $ x = x + 1

以下仍然受支持,但不是首选。

  • 使用$转义美元。$$改用。
  • 修改web.template.Template.globals将全局变量web.template.render作为参数传递
原文地址:https://www.cnblogs.com/stfei/p/10362710.html