Mako templates - jordy33/turbogears_tutorial GitHub Wiki
Mako is a template library written in Python. It provides a familiar, non-XML syntax which compiles into Python modules for maximum performance. Mako's syntax and API borrows from the best ideas of many others, including Django and Jinja2 templates, Cheetah, Myghty, and Genshi. Conceptually, Mako is an embedded Python (i.e. Python Server Page) language, which refines the familiar ideas of componentized layout and inheritance to produce one of the most straightforward and flexible models available, while also maintaining close ties to Python calling and scoping semantics.
Syntax:
${ name }
${"this is some text" | u}
The above expression applies URL escaping to the expression, and produces this+is+some+text. The u name indicates URL escaping, whereas h represents HTML escaping, x represents XML escaping, and trim applies a trim function.
Control Structures
A control structure refers to all those things that control the flow of a program – conditionals (i.e. if/else), loops (like while and for), as well as things like try/except. In Mako, control structures are written using the % marker followed by a regular Python control expression, and are “closed” by using another % marker with the tag “end”, where “” is the keyword of the expression:
% if x==5:
this is some output
% endif
The % can appear anywhere on the line as long as no text precedes it; indentation is not significant. The full range of Python “colon” expressions are allowed here, including if/elif/else, while, for, and even def, although Mako has a built-in tag for defs which is more full-featured.
% for a in ['one', 'two', 'three', 'four', 'five']:
% if a[0] == 't':
its two or three
% elif a[0] == 'f':
four/five
% else:
one
% endif
% endfor
[Back]