Tutorial 1: Creating and rendering a simple template

Here's a simple text template:

	--------------------------------------------------------------
	Welcome to {con:title/}
	
	Features:
	{rep:item} - {con:description/}{/rep:item}
	
	--------------------------------------------------------------

The template contains three tagged areas: con:title, rep:item and con:description. These tags and their contents will be converted into a Template object model by texttemplate. This object model can then be manipulated by 'Controller' functions defined within a Python script. To produce a finished document, data is fed into this Controller which inserts it into the template object model and renders the result. For example:

	--------------------------------------------------------------
	Welcome to Balderdash Pro 5
	
	Features:
	 - New Extended Fubbilizer
	 - Updated Super Knobitzer
	 - Enhanced Virbiled Noxinator
	
	--------------------------------------------------------------


1. First, import the texttemplate module:

	import texttemplate

2. To compile the template object model, call the Template constructor with the template text as its first argument:

	text = '''--------------------------------------------------------------
	Welcome to {con:title/}
	
	Features:
	{rep:item} - {con:description/}{/rep:item}
	
	--------------------------------------------------------------'''

	template = texttemplate.Template(text)

Texttemplate converts each self-closing tag or tag pair into a node within the compiled template. Here's a diagram showing the structure of the resulting object model:

	template
	    |
	    |--- title
	    |
	    |--- item
	    |      |
	    |      |--- description

Tip: You can check the structure of a compiled template or any node within it via the structure() method:

	print template.structure()


3. Next, define the Controller code to insert a title and list of names into the template, then render the result:

	def renderItem(node, description):
		node.description.content = description
	
	def renderTemplate(title, descriptions):
		template.title.content = title
		template.item.repeat(renderItem, descriptions)
		return template.render()

If you need to render more than one document from the compiled template, you can avoid having to recompile it each time by calling its clone() method to create an exact duplicate of the original template object and use this copy instead:

	def renderItem(node, description):
		node.description.content = description
	
	def renderTemplate(title, descriptions):
		tplCopy = template.clone()
		tplCopy.title.content = title
		tplCopy.item.repeat(renderItem, descriptions)
		return tplCopy.render()

4. Finally, call the Controller's main renderTemplate() function to insert some data into the template and render the result:

	title = "Balderdash Pro 5"
	descriptions = ['New Extended Fubbilizer', 'Updated Super Knobitzer', 'Enhanced Virbiled Noxinator']
	print renderTemplate(title, descriptions)

