Creating HTML in python

PythonHtml

Python Problem Overview


I am looking for a way to create html files dynamically in python. I am writing a gallery script, which iterates over directories, collecting file meta data. I intended to then use this data to automatically create a picture gallery, based on html. Something very simple, just a table of pictures.

I really don't think writing to a file manually is the best method, and the code may be very long. So is there a better way to do this, possibly html specific?

Python Solutions


Solution 1 - 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="photos/IMG_5115.jpg">
    </div>
    <div class="photo">
      <img src="photos/IMG_5117.jpg">
    </div>
  </body>
</html>

Disclaimer: I am the author of dominate

Solution 2 - Python

I think, if i understand you correctly, you can see here, "Templating in Python".

Solution 3 - Python

Solution 4 - Python

Python is a batteries included language. So why not use xml.dom.minidom?

from typing import List
from xml.dom.minidom import getDOMImplementation, Document


def getDOM() -> Document:
    impl = getDOMImplementation()
    dt = impl.createDocumentType(
        "html",
        "-//W3C//DTD XHTML 1.0 Strict//EN",
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd",
    )
    return impl.createDocument("http://www.w3.org/1999/xhtml", "html", dt)


def ul(items: List[str]) -> str:
    dom = getDOM()
    html = dom.documentElement
    ul = dom.createElement("ul")
    for item in items:
        li = dom.createElement("li")
        li.appendChild(dom.createTextNode(item))
        ul.appendChild(li)
    html.appendChild(ul)
    return dom.toxml()


if __name__ == "__main__":
    print(ul(["first item", "second item", "third item"]))

outputs:

<?xml version="1.0" ?>
<!DOCTYPE html  PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html>
    <ul>
        <li>first item</li>
        <li>second item</li>
        <li>third item</li>
    </ul>
</html>

The interface does not look like pythonic, but if you have been a fronted developer and used JavaScript DOM manipulation, it matches your mind better and yes it frees you from adding a needless dependency.

Solution 5 - Python

Templating, as suggested in other answers, is probably the best answer (I wrote an early, quirky templating module called yaptu, but modern mature ones as suggested in other answers will probably make you happier;-).

However, though it's been a long time since I last used it, I fondly recall the Quixote approach, which is roughly a "reverse templating" (embedding HTML generation within Python, rather than viceversa as normal templating does). Maybe you should take a look and see if you like it better;-).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRecursionView Question on Stackoverflow
Solution 1 - PythonKnioView Answer on Stackoverflow
Solution 2 - Pythonghostdog74View Answer on Stackoverflow
Solution 3 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 4 - PythonpouyaView Answer on Stackoverflow
Solution 5 - PythonAlex MartelliView Answer on Stackoverflow