Creating HTML in python

Dominate is a Python library for creating HTML documents and fragments directly in code without using templating. You could create a simple image gallery with something like this:

import glob
from dominate import document
from dominate.tags import *

photos = glob.glob('photos/*.jpg')

with document(title="Photos") as doc:
    h1('Photos')
    for path in photos:
        div(img(src=path), _class="photo")


with open('gallery.html', 'w') as f:
    f.write(doc.render())

Output:

<!DOCTYPE html>
<html>
  <head>
    <title>Photos</title>
  </head>
  <body>
    <h1>Photos</h1>
    <div class="photo">
      <img src="https://stackoverflow.com/questions/2301163/photos/IMG_5115.jpg">
    </div>
    <div class="photo">
      <img src="photos/IMG_5117.jpg">
    </div>
  </body>
</html>

Disclaimer: I am the author of dominate

Leave a Comment