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>

2 comments so far

Add Your Comment

  1. Pillspot.org. Canadian Health&Care.No prescription online pharmacy.Special Internet Prices.Best quality drugs. Low price drugs. Order pills online

    Buy:Wellbutrin SR.Advair.Amoxicillin.Ventolin.SleepWell.Female Cialis.Zocor.Aricept.Lasix.Nymphomax.Lipitor.Acomplia.Seroquel.Cozaar.Benicar.Lipothin.Prozac.Buspar.Female Pink Viagra.Zetia….


  2. Medicamentspot.com. Canadian Health&Care.Best quality drugs.Special Internet Prices.No prescription online pharmacy. Low price drugs. Order pills online

    Buy:Cialis Super Active+.Viagra Super Active+.Propecia.Zithromax.Tramadol.Viagra Professional.Cialis Soft Tabs.Cialis Professional.Soma.Levitra.Super Active ED Pack.Viagra Super Force.Viagra.Maxaman.Cialis.Viagra Soft Tabs.VPXL….