Module: Yet Another Python Templating Utility (YAPTU)
Credit: Alex Martelli
Templating is the process of defining a block of text that contains embedded variables, code, and other markup. This text block is then automatically processed to yield another text block, in which the variables and code have been evaluated and the results have been substituted into the text. Most dynamic web sites are generated with the help of templating mechanisms.
Example 3-1 contains Yet Another Python Templating
Utility (YAPTU), a small but complete Python module for this purpose.
YAPTU uses the sub method of regular expressions
to evaluate embedded Python expressions but handles nested statements
via recursion and line-oriented statement markers. YAPTU is suitable
for processing almost any kind of structured-text input, since it
lets client code specify which regular expressions denote embedded
Python expressions and/or statements. Such regular expressions can
then be selected to avoid conflict with whatever syntax is needed by
the specific kind of structured text that is being processed (HTML, a
programming language, RTF, TeX, etc.) See Recipe 3.22 for another approach, in a very different
Python style, with very similar design goals.
YAPTU uses a compiled re object, if specified, to
identify expressions, calling sub on each line of
the input. For each match that results, YAPTU
evaluates match.group(1) as a Python expression and substitutes in place the result, transformed into a string. You can also ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access