DEV Community

Alin Climente
Alin Climente

Posted on • Updated on

How to generate html with Python

I guess we all find out that sending html "over the wire" is faster than using javascript to create components from json data.

Javascript takes longer to be parsed by the browser than html.

First:

pip install htmgem
Enter fullscreen mode Exit fullscreen mode

Here is a simple html boilerplate created with htmgem:


from htmgem.tags import *


html_string = \
html({'lang':'en'}, [
    head([
        meta({'charset':'UTF-8'}),
        meta({'name':'viewport', 'content':'width=device-width, initial-scale=1.0'}),
        link({'rel':'stylesheet', 'href':'https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.1.2/tailwind.min.css'}), 
        script({'src':'https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js', 'defer':None})
    ]),

    body([
        h1("Interesting title"),

        p("""

            A very long paragraph

        """),

        ul({"class": "somediv"}, [
            (li, "item1"),
            (li, "item2"),
            (li, {"id": "myid", "class":"important"}, "item3"),
        ])
    ])
])

Enter fullscreen mode Exit fullscreen mode

All tags are just functions which receive either html/custom attributes either children/text (<a attrs>children</a>).

Add a pinch of AlpineJs for interactivity and you are set.

Checkout the repo here

Top comments (2)

Collapse
 
domonic profile image
domonic

domonic started off similar to this. You can use with...

pip install domonic

pypi.org/project/domonic/

Collapse
 
climentea profile image
Alin Climente

Dominic looks awesome! Definitely more complete than htmgem.