HTM Light: A HTML generator

I’ve been looking for a clean, simple, readable HTML generator library (for any common server-side language) for perhaps a decade now. There are certainly lots of useful libraries around, and templating and MVC systems abound, but nothing quite appealed. I’ve also tried to create my own, but my efforts had always come unstuck, or otherwise I’ve focused on the big-ticket items (i.e. lists and data-tables). I think, though, I may finally have a solution I’m happy with, which should work reasonably well cross-language. Here’s a surprisingly succinct Python version with no dependencies, which I’m calling HTM Light (dedicated to public domain):

HTM Light

class node(object):
    # 'c' is for content
    def __init__(self, tagName, c=None, **attrs):
        self.tagName = tagName
        self.content = c if c else []
        self.attrs = attrs

    def escape(self, s):
        return str(s).replace('&', '&amp;').replace('<', '&lt;') \
            .replace('>', '&gt;').replace('"', '&quot;')

    def __str__(self):
        s = "<"+self.tagName

        # Handle attributes
        for k,v in self.attrs.items():
            s += " " + k + '="'+self.escape(v)+'" ';
        s += ">"

        # Handle content
        for el in self.content:
            s += str(el)

        s += "</"+self.tagName+">"

        return s

Continue reading ‘HTM Light: A HTML generator’ »