Generating HTML documents in python

You can use yattag to do this in an elegant way. FYI I’m the author of the library.

from yattag import Doc

doc, tag, text = Doc().tagtext()

with tag('html'):
    with tag('body'):
        with tag('p', id = 'main'):
            text('some text')
        with tag('a', href="https://stackoverflow.com/my-url"):
            text('some link')

result = doc.getvalue()

It reads like html, with the added benefit that you don’t have to close tags.

Leave a Comment