HTMLTemplate Tutorial 1: Generating a basic links page
(C) 2004 HAS


This tutorial shows how to create a simple links page that'll look something like this:

	--------------------
	|  Site Map
	|
	|  * Home
	|  * Products
	|  * About
	--------------------

1. The following HTML template contains three elements (<title>, <li>, <a>) containing compiler directives (node="con:title", node="rep:item", node="con:link"):

	html = """
	<html>
		<head>
			<title node="con:title">TITLE</title>
		</head>
		<body>
			<ul>
				<li node="rep:item">
					<a href="" node="con:link">LINK</a>
				</li>
			</ul>
		</body>
	</html>
	"""

HTMLTemplate will compile this template to the following object model:

	Template
	    |
	    |----title
	    |
	    |----item
	    |      |
	    |      |----link


2. Both the Template and Repeater ('rep:item') nodes require callback functions to control their rendering.

The main 'renderTemplate' callback function inserts text into the <title> element and generates a list of <li> items:

	def renderTemplate(tem, pagetitle, linksinfo):
		tem.title.content = pagetitle
		tem.item.repeat(renderItem, linksinfo)

This function takes a copy of the Template object as its first argument, followed by two user-supplied arguments containing the data to be inserted into the template:

	pagetitle : string -- the page title
	linksinfo : list of tuple -- a list of form [(URI, name),...]


The repeat() method call in the 'renderTemplate' function takes a second callback function, 'renderItem' to control the rendering of each <li> list item and its <a> element:

	def renderItem(item, linkinfo):
		URI, name = linkinfo
		item.link.atts['href'] = URI
		item.link.content = name


3. Compiling the template is simple. Just create a new Template instance, passing it the 'renderTemplate' function and the HTML template as a string:

	template = HTMLTemplate.Template(renderTemplate, html)


4. To render a page, call the Template object's render() method, passing it any data to be forwarded to the renderTemplate function:

	title = "Site Map"
	links = [('index.html', 'Home'), ('products/index.html', 'Products'), ('about.html', 'About')]
	print template.render(title, links)

Here's the result:

	<html>
		<head>
			<title>Site Map</title>
		</head>
		<body>
			<ul>
				<li>
					<a href="index.html">Home</a>
				</li>
	<li>
					<a href="products/index.html">Products</a>
				</li>
	<li>
					<a href="about.html">About</a>
				</li>
			</ul>
		</body>
	</html>
