2009
03.07

Should be self explanatory

def render(tag):
    if not tag:
        return ""
    else:
        if isinstance(tag, str):
            return tag
        else:
            if len(tag) > 1 and isinstance(tag[1], dict):
                return render_tag(tag[0], tag[1], tag[2:])
            else:
                return render_tag(tag[0], None, tag[1:])

def render_tag(tag, attrs, children):
    if not children:
        return "<%s%s/>" % (tag, render_attrs(attrs))
    else:
        return "<%s%s>%s" % (tag, render_attrs(attrs), "\n".join(map(render, children)), tag)

def render_attrs(attrs):
    return "" if not attrs else " " + " ".join(['%s="%s"' % pair for pair in attrs.items()])

if __name__ == "__main__":

    # example

    html =  ("html",
                ("head",
                    ("title", "this is my title"),
                    ("meta", {"name":"keywords", "value":"python, html"}),
                    ("meta", {"name":"description", "value":"outputting html from python dsl"}),
                    ("script", {"src":"static/js/jquery-1.3.2.min.js"}, None) # None forces open
                ),
                ("body",
                    ("div", 

                    )
                )
            )

    print render(html)

Output from the example is something like this:

<html>
    <head>
        <title>this is my title</title>
        <meta name="keywords" value="python, html"/>
        <meta name="description" value="outputting html from python dsl"/>
        <script src="static/js/jquery-1.3.2.min.js"></script>
    </head>
    <body>
        <div/>
    </body>
</html>

No Comment.

Add Your Comment