yaptoo.py


Purpose: HTML templating.
Download URL: http://science.uwaterloo.ca/~mpalmer/software/yaptoo.py
Summary / Example:
from yaptoo import doTemplate

tmpl='''
<html>
<body>
<table>
#for $x, $y in $rows:
<tr><td>$x</td><td>$y</td></tr>
#end for
</table>
</body>
</html>
'''

rows = [('spam', 'eggs'), ('more spam', 'more eggs')]
print doTemplate(tmpl, globals())
        

As you can see, yaptoo exports a doTemplate function that expects a template definition in a string and a dictionary (or list of dictionaries) containing the data to be used for template substitution. It also takes some optional parameters that control choice of template syntax and caching. These are documented in the module.

You can also see that the syntax is more or less a Cheetah rip-off. (Also like Cheetah, yaptoo is not limited in any way to HTML.) The well-known pun about plagiarism and flattery applies.

Comments / License

Apparently no-one can agree on what templating should be like, and I'm no exception. My take is that the quest for the holy grail of 'separating presentation and logic' is misguided, as the clumsiness of several templating systems taking this principle to the extreme clearly shows. You wind up coding callbacks for trivial string substitutions.

The best solution in Python is Cheetah. However, while I like Cheetah's syntax, I don't like its implementation, which is much too heavy-weight. Thus, I started playing with 'Yaptu' by Alex Martelli and wound up making a couple of changes:

  • separated template parsing from execution, with transparent caching of parsed templates. This makes yaptoo quite fast
  • some error reporting
  • a choice of template syntaxes (but like with yaptu, you can still concoct your own by defining a bunch of regexes). For examples of template syntax, see beginning and end of module.
  • syntax for comments
  • Cheetah-style variable substitution with optional caching of the compiled equivalent Python expressions
  • castrated the use of Python inside templates by limiting flow control to for and if

Limitations:

  • Statements, expressions, or comments cannot span multiple lines
  • for loops have neither break nor continue
  • No #include functionality

Also note that yaptoo has no 'controller' behaviour of any kind, i.e. you cannot run templates in a 'standalone' fashion as with Cheetah. yaptoo is intended solely for use in an auxiliary role. I typically put the template definitions inside my servlet files anyway (heaven forbid!), since I see no point in separating them. (Obviously I don't use WYSIWYG editors.)

License: Python.


You might also be interested in JSResolver, a Python module for recursive dependency resolution and compression of JavaScript files.

Created and maintained by Michael Palmer.