Home > Articles > Programming > C/C++

  • Print
  • + Share This
From the author of Generating HTML

Generating HTML

The actual HTML output uses the ETXMLWriter class from EtoileFoundation. This is based loosely on the Seaside HTML writer, which makes heavy use of blocks in Smalltalk to represent nesting of HTML elements. You can use ETXMLWriter without blocks, but using blocks makes it much easier to understand the output. The important method is:

- (void)startAndEndElement: (NSString*)aName
                attributes: (NSDictionary*)attributes
                containing: (id)aBlock;

This opens an XML tag, executes aBlock, and then closes the tag. For example, you might call it like this:

[aWriter startAndEndElement: @"ol"
                 attributes: nil
                 containing: ^()
        for (id element in list)
            [aWriter startAndEndElement: @"li"
                                  cdata: element];

This would create an HTML ordered list, with a list item for each entry in the collection. The advantage of using blocks here is that you don't have to think about closing the <ol> tag—it is closed automatically. The code is quite easy to read, because the structure of the code corresponds to the structure of the output.

This use of blocks adds a little bit of overhead, but if the code isn't in a performance-critical section it doesn't matter. Using blocks like this can make anything that generates hierarchical output a lot simpler to read.

  • + Share This
  • 🔖 Save To Your Account