views:

79

answers:

6

I'm hacking a quick and dirty python script to generate some reports as static html files.

What would be a good module to easily build static html files outside the context of a web application?

My goals are simplicity (the HTML will not be very complex) and ease of use (I don't want to write a lot of code just to output some html tags).

I found two alternatives on my first goolge search:

Also, I feel that using a templating engine would be over-kill, but if you differ please say it and why.

Any other recommendation?

+4  A: 

Maybe you could try Markdown instead, and convert it to HTML on the fly?

clee
Hmmm... Nice idea. Will consider it for sure.
Sergio Acosta
+2  A: 

You don't necessarily need something complex - for instance, here's a ~150 line library to generate HTML in a functional manner:

http://github.com/Yelp/PushmasterApp/blob/master/pushmaster/taglib.py

(Full disclosure, I work with the person who originally wrote that version, and I also use it myself.)

Amber
Thanks!, I will check it out. Specially, thanks for recommending something that you have used.
Sergio Acosta
+1  A: 

Why would a templating engine necessarily be overkill? You don't need the whole web framework just to use the templating engine (at least, for most templating engines). Mako for example can be used stand-alone just fine, and I often use it to generate html files (reports from a db and such)

Steven
+1  A: 

i recommend having a look at shpaml

flow
+1  A: 

If you have just some simple static HTML files. Then why not use string templates like so.

import string

TEMPLATE_FORMAT = """
<html>
<head><title>Trial</title></head>
<body>
    <div class="myclass">$my_div_data</div>
</body>
"""
my_div_data = "some_data_to_display_in_HTML"
TEMPLATE    = string.Template(TEMPLATE_FORMAT)
html_data   = TEMPLATE.safe_substitute(my_div_data)
open("out.html", "w").write(html_data)

Give this a shot if you don't have too big HTML files to generate. Saves you on the learning you need to do if you decide to use libraries.

MovieYoda
+1  A: 

ElementTree can produce html with some limitations. I'd write it like this:

from xml.etree.ElementTree import ElementTree, Element, SubElement
import sys 

html = Element('html')

head = SubElement(html, 'head')
style = SubElement(head, 'link')
style.attrib = {'rel': 'stylesheet', 'href': 'style.css', 'type': 'text/css'}
body = SubElement(html, 'body')

para = SubElement(body, 'p')
para.text = 'Lorem ipsum sit amet'

doc = ElementTree(html)
doc.write(sys.stdout)

In case of moderately complex html I'd stick with some templating engine: Jinja2, Mako, Cheetah, just to name a few.

eGlyph