web.py 文档中文翻译:web.py 模板系统 (代码名称templetor)

原文:web.py templating system (codename: templetor)

There are almost as many Python templating systems as there are web frameworks (and, indeed, it seems like many templating systems are adopting web framework-like features), so it is with some trepidation that I work on a new one. Sadly, again I find that my requirements are met by nothing else:
Python 模板系统几乎和web框架一样多(甚至一些 web 框架的特色是拥有多个模板系统。)我总是带着忧虑使用一个新的。令人沮丧的,但是我发现我只需要:

1. The templating system has to look decent. No crud.
1. 这个模板系统看起来不错。不混乱。
2. Reuse Python terms and semantics as much as possible.
2. 尽可能的使用 Python 关键字和语法。
3. Expressive enough to do real computation.
3. 充足的表达式用于真正使用
4. Usable for any text language, not just HTML and XML.
4. 可用于任何文本语言,不要只支持 HTML 和 XML。

And requirements for the implementation as well:


1. Sandboxable so that you can let untrusted users write templates.
1. 沙盒支持,使得你可以允许未信任的用户写模板。
2. Simple and fast implementation.
2. 简单和快速的使用

So here’s my entry.
Variable substitution

[coolcode lang=”python”]
Look, a $string.
Hark, an ${arbitrary + expression}.
Gawk, a $dictionary[key].function(‘argument’).
Cool, a $(limit)ing.

Stop, \$money isn’t evaluated.

We use basically the same semantics as (rejected) PEP 215. Variables can go anywhere in a document.
我们使用基本上和(不合格?) PEP 215 一样的语义。变量可以在文档的任何地方。
Newline suppression

[coolcode lang=”python”]
If you put a backslash \
at the end of a line \
(like these) \
then there will be no newline.

renders as all one line.

[coolcode lang=”python”]
Here are some expressions:

$for var in iterator: I like $var!

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

That’s all, folks.

All your old Python friends are here: if, while, for, else, break, continue, and pass also act as you’d expect. (Obviously, you can’t have variables named any of these.) The Python code starts at the $ and ends at the :. The $ has to be at the beginning of the line, but that’s not such a burden because of newline suppression (above).
你所有的旧的 Python 朋友在这里:if, while, for, else, break, continue, 和 pass 也为你预期的动作。(明显你不能将变量名称设置为这些。)这些 Python 代码以 $ 开头,以 : 结尾。 $ 在行开始位置,只是叠句因为新行抑制所以不是这样(上面)

Also, we’re very careful about spacing — all the lines will render with no spaces at the beginning. (Open question: what if you want spaces at the beginning?) Also, a trailing space might break your code.
同样,我们非常小心空白 – 所有的行会呈现为开始出没有空白。(问题:如果你需要行开始出有空白怎么做?)同样,结尾处的空白可终止你的代码。

There are a couple changes from Python: for and while now take an else clause that gets called if the loop is never evaluated.
有两个和python不同的更改:for 和 while 现在获得 else 子句,它将在从未执行循环体内代码时执行。

(Possible feature to add: Django-style for loop variables.)
(可能增加的特征:Django-style 循环变量)

[coolcode lang=”python”]
$# Here’s where we hoodwink the folks at home:

Please enter in your deets:

CC: [ ] $#this is the important one
SSN: $#Social Security Number#$ [ ]

Comments start with $# and go to #$ or the end of the line, whichever is first.

注释开始与 $# , 结束与 #$ 或行结尾。

NOTE: This feature has not been implemented in the current web.py implementation of templetor.

[coolcode lang=”python”]
Sometimes you just need to break out the Python.

$ mapping = {
$ ‘cool’: [‘nice’, ‘sweet’, ‘hot’],
$ ‘suck’: [‘bad’, ‘evil’, ‘awful’]
$ }

Isn’t that $mapping[thought]?
That’s$ del mapping $ fine with me.

$ complicatedfunc()

$ for x in bugs:
$ if bug.level == ‘severe’:
Ooh, this one is bad.
$ continue
And there’s $x…

Body of loops have to be indented with exactly 4 spaces.

Code begins with a $ and a space and goes until the next $ or the end of the line, whichever comes first. Nothing ever gets output if the first character after the $ is a space (so complicatedfunc above doesn’t write anything to the screen like it might without the space).
代码开始与 $ 和 一个空白 ,直到下一个 $ 或者 行结束。绝不输出$之后的第一个空白(那么执行上面代码绝不输出空白)
Python integration
Python 集成

A template begins with a line like this:

[coolcode lang=”python”]
$def with (name, title, company=’BigCo’)

which declares that the template takes those arguments. (The with keyword is special, like def or if.)
声明使用哪些参数。(with 关键字是专用的, like def or if.)

Don’t forget to put spaces in the definition

The following will not work:

[coolcode lang=”python”]
$def with (name,title,company=’BigCo’)

Inside Python, the template looks like a function that takes these arguments. It returns a storage object with the special property that evaluating it as a string returns the value of the body of the template. The elements in the storage object are the results of the defs and the sets.
这个模板的样子像 Python 内部一个程序使用这些参数。它返回一个和这个模板相关的对象,这个对象模仿字符串的行为。The elements in the storage object are the results of the defs and the sets.

Perhaps an example will make this clearer. Here’s a template, “entry”:

[coolcode lang=”python”]
$def with (post)

$var title: $post.title



Here’s another; “base”:

[coolcode lang=”python”]
$def with (self)




Now let’s say we compile both from within Python, the first as entry, the second as base. Here’s how we might use them:
现在假定说我们在 Pyhon 中使用两者,第一个是 entry,第二个是 base。我们应该使用:

[coolcode lang=”python”]
print base( entry( post ) )

entry takes the argument post and returns an object whose string value is a bit of HTML showing the post with its title in the property title. base takes this object and places the title in the appropriate place and displays the page itself in the body of the page. The Python code prints out the result.

_Where did markdown come from? It wasn’t passed as an argument._ You can pass a list of functions and variables to the template compiler to be made globally available to templates. Why $:self? See below

Here’s an example:

[coolcode lang=”python”]
import template
render = template.render(‘templates/’)
template.Template.globals[‘len’] = len

print render.base(render.message(‘Hello, world!’))

The first line imports templetor. The second says that our templates are in the directory templates/. The third give all our templates access to the len function. The fourth grabs the template message.html, passes it the argument ‘Hello, world!’, passes the result of rendering it to the template base.html and prints the result. (If your templates don’t end in .html or .xml, templetor will still find them, but it won’t do its automatic HTML-encoding.)

Turning Off Filter

By default template.render will use web.websafe filter to do HTML-encoding. To turn it off, put a : after the $ as in:

[coolcode lang=”python”]

Output from form.render() will be displayed as is.

[coolcode lang=”python”]
$:fooBar $# fooBar = lorem ipsum

Output from variable in template will be displayed as is.
Including / nesting templates

If you want to nest one template within another, you nest the render() calls, and then include the variable (unfiltered) in the page. In your handler:

[coolcode lang=”python”]
print render.foo(render.bar())

or (to make things a little more clear):

[coolcode lang=”python”]
barhtml = render.bar()
print render.foo(barhtml)

Then in the template foo.html:

[coolcode lang=”python”]
$def with (bar)
html goes here
more html

This replaces the $:bar with the output of the render.bar() call (which is why it must be $:/unfiltered, so that you get un-encoded HTML (unless you want something else of course)). You can pass variables in, in the same way:

[coolcode lang=”python”]

print render.foo(render.bar(baz), qux)

In the template bar (bar.html):

[coolcode lang=”python”]
$def with (baz)
bar stuff goes here + baz

In template foo (foo.html):

[coolcode lang=”python”]
$def with (bar, qux)
html goes here
Value of qux is $qux