5.5 Tag Rewriting

Draco makes it possible for you to modify the html output of a template in a modest way. For each html element, it is possible to define a function that can change the tag's attributes and append some literal text after the opening tag. This feature is called tag rewriting.

Internally, this functionality is used by Draco to add a session identifier to internal links, to implement image size detection and to provide for automated form feedback. For you, the developer, only your imagination is the limit. One idea would be to use this feature to add compatibility attributes such as width and bgcolor to some tags when an older browser is detected. This way you can keep your html uncluttered for newer, compatible browsers but you can support noncompatible browsers too.

There are two ways to install tag rewriter functions. In both ways you need to subclass Draco's Rewriter class (found in draco.rewrite) and define methods that correspond to tags with the same name. This class is called the rewriter class.

If you want to install a global rewriter that is in effect for all templates in the web application, you can put the rewriter class in a file named __rewrite__.py in the document root of your web site. Draco will automatically detect and use it. If this file is changed it will be automatically reloaded.

The second way to install a rewriter function is to call the install() method of the Rewriter class. Rewriter functions installed this way are in effect only for the duration of the current request.

The following example illustrates how to define a rewrite function for the <table> tag. The rewriter adds a cellpadding=0 attribute.

from draco.rewrite import Rewriter

class MyRewriter(Rewriter):

    def table(self, tag):
	tag.attrs['cellpadding'] = '0'

class Rewriter( )
Base class for all rewriter functions.

The Rewriter class has one public method:

install( )
Install the rewriter for the current request.

When a tag rewriter function is called, it is passed an instance of a Tag object. The rewriter can modify the tag through this object.

class Tag( name, [attrs={}])
Class used to modify tags in rewriter functions.

The public attributes and methods of Tag are:

name
The tag name, i.e. 'a', or 'table'. This attribute may be changed but changes to it will only update the opening tag, not the closing tag of the html element.

attrs
A dictionary containing all the attributes of the html tag. Changes to this dictionary will change the tag's attributes in the html output correspondingly. Attributes without value have a value of None.

endstyle
The end style of the opening tag, which will be one of '>', '/>' or ' />'. The initial value of this attribute is detected from the template and can be modified by the user. The end style is important for empty xhtml tags like <br>, which should be <br/> in xhtml.

appendText( text)
Append the literal text text after the opening tag of the html element.