1 | # Yet Another Template Language |
---|
2 | |
---|
3 | This is the web2py template language described [here](http://web2py.com/books/default/chapter/29/05/the-views) made available as stand alone package so it can be used anywhere. |
---|
4 | |
---|
5 | Basically it is pure Python within "{{" ... "}}" delimiters and blocks are terminated with "pass" if termination is not obvious. There is no indentation constraints. |
---|
6 | |
---|
7 | For example: |
---|
8 | |
---|
9 | ``` |
---|
10 | from yatl import render, SPAN |
---|
11 | |
---|
12 | example = """ |
---|
13 | <div> |
---|
14 | {{ for k in range(num): }} |
---|
15 | <span>{{=SPAN(k, _class='number')}} is {{if k % 2 == 0:}}even{{else:}}odd{{pass}}</span> |
---|
16 | {{ pass }} |
---|
17 | </div> |
---|
18 | """ |
---|
19 | |
---|
20 | print(render(example, context=dict(num=10, SPAN=SPAN), delimiters="{{ }}")) |
---|
21 | ``` |
---|
22 | |
---|
23 | In the example SPAN is an optional helper. |
---|
24 | Output is escaped by default unless marked up with the XML helper as in {{=XML('1 < 2')}}. |
---|
25 | Note that the helpers included here are similar but not identical to the web2py ones. |
---|
26 | They are 99% compatible but the implementation is different. |
---|
27 | |
---|
28 | Any Python expressions is allowed in templates, including function and class defintions: |
---|
29 | |
---|
30 | ``` |
---|
31 | example = """ |
---|
32 | {{ def link(x): }}<a href="{{=x}}">{{=x}}</a>{{ pass }} |
---|
33 | <ul> |
---|
34 | {{ for k in range(num): }} |
---|
35 | <li> |
---|
36 | {{= link('http://example.com/%s' % k) }} |
---|
37 | </li> |
---|
38 | {{ pass }} |
---|
39 | </ul> |
---|
40 | """ |
---|
41 | |
---|
42 | print(render(example, context=dict(num=10), delimiters="{{ }}")) |
---|
43 | ``` |
---|
44 | |
---|
45 | ## Caching |
---|
46 | |
---|
47 | If you implement a caching reader as the one below, you mak yatl even faster: |
---|
48 | |
---|
49 | ``` |
---|
50 | CACHE = {} |
---|
51 | def reader(filename): |
---|
52 | if filename in CACHE: |
---|
53 | return CACHE[filename] |
---|
54 | with open(filename) as fp; |
---|
55 | CACHE[filename] = content = fp.read() |
---|
56 | return content |
---|
57 | |
---|
58 | output = yatl.render(reader(filename), path=path, reader=reader) |
---|
59 | ``` |
---|
60 | |
---|