6.3.2 Custom Tag Example

Here is an example of a custom tag module that does the basic functionality of the HTML tags <UL> and <LI>.

from pse_handler.api import CustomTag

class List(CustomTag):

    # this is the same as the default, but this is how you could define
    # a different tag name from the class name
    _name = 'list'

    def __init__(self, id = None, type = 'square'):
        # this is similar to the <UL> tag but defaults to "square"
        if self.needs_init:
            CustomTag.__init__(self, id)
            self.type = type

    def add(self, thing):
        # only add bona fide Item objects
        if isinstance(thing, Item):
            CustomTag.add(self, thing)

    def addString(self, text):
        # ignore bare HTML not in an Item tag
        pass

    def __str__(self):
        # construct the unordered list html
        result = [ '<ul type="%s">' % self.type ]
        result.append(CustomTag.__str__(self))
        result.append('</ul>')
        return '\n'.join(result)

class Item(CustomTag):

    def __str__(self):
        # make a list item from the _contents
        result = [ '  <li>' ]
        result.append(CustomTag.__str__(self))
        result.append('</li>')
        return ''.join(result)

Sample usage is as follows:

<list>
<item>This is the first item</item>
<item>This is the second item</item>
</list>
which produces the following output:
<ul type="square">
  <li>This is the first item</li>
  <li>This is the second item</li>
</ul>