Controlling template rendering
Template rendering is controlled by a user-defined function, typically named render_template
, that's attached to the Template
object as it's created and triggered automatically each time the Template
object's render
method is called.
When the template's render
method is called, the Template
object calls its attached render_template
function, passing it a copy of itself along with any additional arguments passed via the render
call. This allows the renderTemplate function to manipulate this object model - inserting the user-supplied data into nodes as tag attributes and content, omitting unwanted sections, even rearranging the object model itself(!). Once the render_template
function returns, the now-modified object model is rendered to text and returned.
It's also possible to manipulate the template object model directly, prior to calling its render
method. This can be useful if you have some data you want to appear in every rendered page but don't wish to re-render it each time for efficiency's sake.
Compiling a template
A single Template
object can be used to render any number of pages.
To compile a template, create a new instance of HTMLTemplate's Template
class with the main callback function and the HTML text as arguments:
template = HTMLTemplate.Template(render_template, html)
Two optional arguments may also be provided:
- node
- The name of the tag attributes used to hold compiler directives. The default is
node
, but may be changed to any other valid attribute name; e.g.id
,obj
,foo:bar
. This can be useful if, for example, you have to edit or process your templates in an application that automatically rejects all non-valid HTML attribute names. - codecs
- Allows the default HTML entity encoding/decoding functions to be replaced. These functions are applied when getting or setting the value of a
Container
orRepeater
node's content property. By default, only the four markup characters,<>&"
are converted. This minimal level of conversion is provided for security's sake, but you may want to replace these functions with your own if you need also to escape non-ASCII or other characters as standard.