DEV Community

Alin Climente
Alin Climente

Posted on • Edited on

4 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

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.

Sentry blog image

Identify what makes your TTFB high so you can fix it

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

Read more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay