3.12 Displaying Tree Structured Data
Description: Displaying Tree Structured Data
Keywords: albatross

#
3.12 Displaying Tree Structured Data

One of the more powerful tags in the Albatross toolkit is the `<al-tree>` tag. This tag can be used to display almost any data that is tree structured.

The best way to explain the tag is by example. Consider the `samples/templates/tree/tree.py` sample program. This is a standalone program that is intended to be run from the command line.

    from albatross import SimpleContext

    class Node:

        def __init__(self, name, children = None):
            self.name = name
            if children is not None:
                self.children = children

    ctx = SimpleContext('.')
    ctx.locals.tree = Node('a', [Node('b', [Node('c'),
                                            Node('d')]),
                                 Node('e', [Node('f', [Node('g', [Node('h'),
                                                                  Node('i')])]),
                                            Node('j'),
                                            Node('k', [Node('l'),
                                                       Node('m')])])])
    templ = ctx.load_template('tree.html')
    templ.to_html(ctx)
    ctx.flush_content()

The program constructs a tree of `Node` objects then passes the root of the tree to the `tree.html` template for formatting. The `samples/templates/tree/tree.html` template file looks like this:

    <al-lookup name="indent">
     <al-item expr="0">  </al-item>
     <al-item expr="1"> |</al-item>
     <al-item expr="2"> \</al-item>
    </al-lookup>
    <al-tree iter="n" expr="tree">
     <al-for iter="c" expr="range(n.depth())">
      <al-value expr="n.line(c.value())" lookup="indent">
     </al-for>
     -<al-value expr="n.value().name" whitespace="newline">
    </al-tree>

When you run the program it produces the following result.

    -a
     |-b
     | |-c
     | \-d
     \-e
       |-f
       | \-g
       |   |-h
       |   \-i
       |-j
       \-k
         |-l
         \-m

Internally the `<al-tree>` tag uses a special iterator that is an instance of the `TreeIterator` class. This iterator performs a pre-order traversal of the tree returned by the `expr` attribute of the tag. The only requirement of the tree node objects is that child nodes are stored in the `children` sequence member.

The `<al-tree>` tag also supports a more powerful lazy loading mode of operation which is supported by Albatross application objects. Refer to section 5.3.10.