Introduction
In a previous post, we setup a simple echo application using Django Channels. In this post, we will extend that application to use htmx.
htmx is a library that allows you to access AJAX, WebSockets, and Server Sent Events directly in your HTML.
Modifying the template
We'll load htmx and the required Websocket Extension via a CDN and update our template to use htmx. Replace the contents of index.html
with the following:
<!DOCTYPE html>
<html>
<head>
<title>Echo</title>
</head>
<body hx-ext="ws" ws-connect="/ws/echo/">
<h1>Echo Test</h1>
<!-- Specify the target for the response -->
<span id="reply"></span>
<!-- Attach ws-send to a form -->
<form ws-send>
<input type="text" name="message">
<button type="submit">Send</button>
</form>
<script src="https://unpkg.com/htmx.org@2.0.3"></script>
<script src="https://unpkg.com/htmx-ext-ws@2.0.1/ws.js"></script>
</body>
</html>
We will also need to modify the consumer in core/consumers.py
to deliver the message in hypertext.
import json
from channels.generic import websocket
class EchoConsumer(websocket.WebsocketConsumer):
def receive(self, text_data):
json_data = json.loads(text_data)
message = json_data['message']
response = f'<span id="reply">{message}</span>'
self.send(text_data=response)
How it works?
- On page load, the Websocket extension is loaded via
hx-ext="ws"
. - htmx will connect to an enpoint specified by
ws-connect="/ws/echo/"
. (Do not forget the trailing slash!) - htmx will keep reconnecting every 1 second as long as there are failures, errors or aborts.
- When a form with
ws-send
attribute is submitted (in this example via the "Enter" key or clicking "Send"), htmx will send the form data to the websocket consumer. - The consumer will receive the message as json text, convert to a dictionary and extract the message.
- htmx will be expecting a response that can be swapped into the DOM. In this case, we are sending back a span with the message.
- htmx will find the corresponding ID in the DOM, and replace the contents with the new message via Out of Band Swap