H is for htmx - Python A to Z
Code in this blog post was written with versions: Python: 3.14
Python A-Z is a blog series about Python. Each day, I share insights, ideas and examples for different parts of Python development that match with the letter of the day. Blaugust is an annual blogging festival in August where the goal is to write a blog post every day of the month.
For the past couple of years, all my new Django projects have been built with htmx and I’ve worked on couple of other, non-Django projects that uses it as well. It’s a blast!
It took me a while to get used to but especially this demo by Michael Kennedy at PyBay 2021 convinced me of its utility and looking back now, I love how simple it makes building most interactive websites and web apps.
htmx is a small (16k) Javascript library that makes it possible to build modern UIs by transferring HTML over the wire instead of JSON. Combined with Django’s templating system, it makes build smooth, fluid frontends with server-side rendering.
Here’s an example from my Pokémon TCG inventory application. I have a component for showing a card and a (-) [count] (+) style UI for it.
<button
name="decrease-qty"
id="{{card.id}}-{{variant.variant|slugify}}"
data-foil="{{variant.variant}}"
hx-put="/collection/decrease/{{variant.id}}/"
hx-target="input#{{card.id}}-{{variant.variant|slugify}}"
hx-swap="outerHTML"
>
-
</button>
Here’s a button that decreases the amount in my database. It uses three htmx
attributes: hx-put,
hx-target and
hx-swap.
hx-put tells the code to send a PUT
request to the provided endpoint when this button is clicked.
hx-target tells which element the
returned HTML in the response should go into.
hx-swap tells how to change it: in this
case, replace the entire HTML element of the target.
I click the button in the UI, a PUT is sent to the server that updates the
count in the database and sends back HTML that in this case is an
input with the value of the new
count (and some extra htmx controls so I can change the value directly in the
input as well).
HTMX 4.0, the first JavaScript library to release exclusively on the Game Boy® platform!
There’s also a Game Boy game by htmx and Seth Larson made a video and wrote a blog post about it.
If something above resonated with you, let's start a discussion about it! Email me at juhis@hamatti.org and share your thoughts. This year, I want to have more deeper discussions with people from around the world and I'd love if you'd be part of that.