By simplifying the process of building modern web applications, HTMX reduces complexity and helps developers create feature-rich apps with an improved user experience, more efficiently.
In this guide, we demonstrate how to create a dynamic process log view using HTMX and Django. The log view will automatically update when new entries are added and allows users to filter the displayed entries based on metadata. This serves as a practical example of HTMX's capabilities when integrated with Django.
1. What is HTMX and why use it?
2. Setting up the HTML structure
Our approach is to use a form for filter parameters and a log view for displaying all messages. Although we primarily use Django at Wildfish, HTMX is backend-independent. The backend code for generating responses can be found in the repository, but we'll focus on the HTMX results in this post.
Here's the fully rendered HTML on page load:
Upon loading, the log container requests
/_/log-list replacing the
LOADING... content with the response. When a filter is selected, a request is made to
/_/select-filter and HTMX processes the response and replaces the necessary components.
3. Implementing the filter form
HTMX allows requests to be sent when an input element is clicked, passing the name and value as query parameters to the requested URL. We can use this to request a filtered version of the log component.
Each radio button has a hx-get attribute, telling HTMX to request the provided URL and update the DOM using the response. The response from
/_/select-filter will look something like:
Key elements to note are:
The hx-swap-oob property: This instructs HTMX to perform an "Out of Band" swap, allowing it to swap an element that isn't the current target. In this case, the value
outerHTML:#log-container tells HTMX to replace the content of the #log-container element and the entire element due to the
The new hx-get value on the
#log-list element now includes the filter parameter, so only logs for that filter are returned.
Once the request is processed, HTMX stops polling the old log URL and starts requesting the new, filtered log URL.
If you encounter any issues or questions, feel free to raise an issue on the GitHub project or comment below.
The GOV.UK Design System is a toolkit and a set of guidelines for creating sites and services for Her Majesty's Government which are clear and consistent and accessible.
MangoPay presents itself as "Payments for Marketplaces", but it's far from being just a payment provider...