Templetor
Originally the templating language for web.py
, I've ported it to modern python for webint
and added RestrictedPython support.
Examples
For python webapps: canopy python project
For writing posts/pages: post body renderer in webint-posts app and this page's source
History
The web.py template language, called Templetor is designed to bring the power of Python to templates. Instead of inventing new syntax for templates, it re-uses python syntax. If you know the Python programming language, you will be at home.
—webpy.org/docs/0.3/templetor
Security
Templetor intentionally limits variable access within a template. A user has access to the variables passed into the template and some builtin python functions. This allows untrusted users to write templates, and not worry about them causing harm to the running system. You can, of course, increase the global variables available.
—webpy.org/docs/0.3/templetor
RestrictedPython is a tool that helps to define a subset of the Python language which allows to provide a program input into a trusted environment.
—github.com/zopefoundation/RestrictedPython
Templetor generates an AST representation of the template that is then passed through RestrictedPython. A few default restrictions are relaxed and "safe builtins" are allowed, see templating.py
.
Usage
Syntax
Expression Substitution
Special character $ is used to specify python expressions. Expression can be enclosed in () or {} for explicit grouping.
Look, a $string. Hark, an ${arbitrary + expression}. Gawk, a $dictionary[key].function("argument"). Cool, a $(limit)ing.
Assignments
Sometimes you may want to define new variables and re-assign some variables.
$ bug = get_bug(id) <h1>$bug.title</h1> <div>$bug.description</div></pre> Notice the space after $ in the assignment. It is required to differentiate assignment from expression substitution.
Filtering
By default, Templetor uses web.websafe filter to do HTML-encoding.
$ foo = "<div>bar</div>"
To turnoff filter use : after $. For example, the following will not be html escaped:
$foo
<div>bar</div>
$:foo
<div>bar</div>
Newline Suppression
Escaping $
Comments
Control Structures
Other Statements
Builtins & Globals
$web
Transaction Context
$web.tx
Query parameters:
$web.tx.request.uri.query
Example:
{'bat': ['baz'], 'foo': ['bar']}
HTTP Requests
$ homepage = web.get("ragt.ag") $homepage.card