3. Tutorial 1: Generating a basic links page

Introduction

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

web page containing a list of links

1. Define the HTML template

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

<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>

Note that another attribute name, e.g. id, may be used instead of node if preferred.

HTMLTemplate will compile this template to the following object model:

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

2. Write the template controller

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

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

def render_template(tem, pagetitle, linksinfo):
    tem.title.content = pagetitle
    tem.item.repeat(render_item, 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 render_template function takes a second callback function, render_item to control the rendering of each <li> list item and its <a> element:

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

3. Compile the HTML Template

Compiling the template is simple. Just create a new Template instance, passing it the render_template function, HTML template string and, optionally, the name of the attribute used to define compiler directives, e.g. attribute='id':

template = HTMLTemplate.Template(render_template, html)

4. Render a page

To render a page, call the Template object's render() method, passing it any data to be forwarded to the render_template 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>