|
Call Graph |
Given a template string containing inline python source code, return a
python function that will fill in the template, and output the result.
The signature for this function is taken from the first line of
docstring . Output is generated by making repeated calls to
the output function with the given name (which is typically one of the
function's parameters).
The templating language used by this function passes through all text
as-is, with three exceptions:
-
If every line in the template string is indented by at least x spaces, then the first x
spaces are stripped from each line.
-
Any line that begins with '>>>' (with no indentation)
should contain python code, and will be inserted as-is into the
template-filling function. If the line begins a control block (such
as 'if' or 'for'), then the control block will be closed by the first
'>>>'-marked line whose indentation is less than or equal to
the line's own indentation (including lines that only contain
comments.)
-
In any other line, any expression between two '$' signs will be
evaluated and inserted into the line (using
str() to
convert the result to a string).
Here is a simple example:
>>> TEMPLATE = '''
... <book>
... <title>$book.title$</title>
... <pages>$book.count_pages()$</pages>
... >>> for chapter in book.chapters:
... <chaptername>$chapter.name$</chaptername>
... >>>
... </book>
>>> write_book = compile_template('write_book(out, book)', TEMPLATE)
Acknowledgements:
The syntax used by compile_template is loosely
based on Cheetah.
|