5.1.1 Extending the Simple Renderer

Now that we have a simple renderer working, it is very simple to extend it to do more specific operations. Let’s say that the default renderer is fine for most nodes, but for the \section node we want to do something special. For the section node, we want the title argument to correspond to the title attribute in the output XML1. To do this we need a method like the following.

def handle_section(node):
    return u'\n\n<%s title="%s">\n%s\n</%s>\n' % \
            (node.nodeName, unicode(node.attributes['title']), 
             unicode(node), node.nodeName)

Now we simply insert the rendering method into the renderer under the appropriate key. Remember that the key in the renderer should match the name of the node you want to render. Since the above rendering method will work for all section types, we’ll insert it into the renderer for each LaTeX sectioning command.

renderer = Renderer()
renderer['section'] = handle_section
renderer['subsection'] = handle_section
renderer['subsubsection'] = handle_section
renderer['paragraph'] = handle_section
renderer['subparagraph'] = handle_section

Running the same LaTeX document as in the previous example, we now get this output.

Previous paragraph.

<section title="My Section">
 Centered text with &lt;, &gt;, and &amp; charaters.
Next paragraph.


Of course, you aren’t limited to using just Python methods. Any function that accepts a node as an argument can be used. The Zope Page Template (ZPT) renderer included with plasTeX is an example of how to write a renderer that uses a templating language to render the nodes (see section 5.3).


  1. This will only work properly in XML if the content of the title is plain text since other nodes will generate markup.