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

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

class Item(CustomTag):

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

Sample usage is as follows:

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