2023-03

2023-03-06 Using the Django messages framework with HTMX’s OOB swaps by Benoit Blanchon

In my previous article , I showed you how to integrate the Django messages framework with HTMX thanks to the HX-Trigger header and some JavaScript code.

Today, we’ll see an alternative (and probably better) way to do this using out-of-band swaps.

I won’t do a tutorial because it would be too similar to my previous article; instead, I’ll focus on the key elements of this pattern.

You can find the corresponding source code in the oob branch of the dedicated GitHub repository.

You can find an extended version of this article on YouTube. Overview

Here is how the previous technique works:

  • It all starts with a button with the hx-get attribute.

  • When the user clicks on this button, HTMX performs a GET request which triggers the execution of a Django view.

  • The view creates an HTTP response and publishes one or more messages.

  • The response is intercepted by our middleware.

  • The middleware pulls the messages and stores them in the HX-Trigger header of the response.

  • The response goes over the wire and is received by HTMX.

  • HTMX updates the page with the response body.

  • When it sees the HX-Trigger header, it calls a JavaScript function.

  • This function creates the toasts and adds them to the DOM.

  • Finally, the browser displays the toasts along with the updated page.

As you see, we don’t need much JavaScript with this new version because we piggybacked the toasts to the page.

This is what HTMX calls out-of-band swaps. They are “out of band” because they are not part of the primary swap; instead, they target specific elements in the DOM.

This technique is more in line with HTMX’s philosophy of rendering the HTML in the backend.

Conclusion

Honestly, I still haven’t fully made up my mind: is this technique superior to the one using HX-Trigger? Sure, it seems better since we removed the clumsy JavaScript and simplified the template. However, we carelessly appended content to the response body, and I wonder if this is always possible. Moreover, the issue with empty responses bothers me because I really like this trick.

For these reasons, I still use the old technique on my projects and don’t plan to upgrade them yet .