ambient-digital
Published in

ambient-digital

Interactive zero Javascript sites with django

How to rocket-start your frontend with HTMX

Photo by SpaceX on Unsplash

A new hope

<button hx-post="/clicked" hx-swap="outerHTML">
Click Me
</button>
Photo by Faris Mohammed on Unsplash

That’s neat! But…

Example sketch of our ticket dashboard

The magic of events

<span class="badge"    
hx-get="tickets/open/count"
hx-trigger="ticketCounterHasChanged from:body"
hx-swap="innerHTML">
27
</span>

Marrying django and HTMX

// Add CSRF token to HTMX plugin for being able to make AJAX calls
document.body.addEventListener('htmx:configRequest', (event) => {
event.detail.headers['X-CSRFToken'] = '{{ csrf_token }}';
});

View and Header

class CloseTicketView(generic.View):
http_method_names = ('post',)
def post(self, request, *args, **kwargs):
# fetch ticket and close it

# Build response
response = render(
request,
'/ticket/partials/_closed_ticket.html',
{'ticket': ticket})
response['HX-Trigger'] = 'ticketCounterHasChanged'
return response
Photo by Benjamin Sharpe on Unsplash

Multiple Events

class CloseTicketView(generic.View):
http_method_names = ('post',)
def post(self, request, *args, **kwargs):
...
# Build response
response = render(
request,
'/ticket/partials/_closed_ticket.html',
{'ticket': ticket})

response['HX-Trigger'] = json.dumps({
'ticketCounterHasChanged': '-',
'updateSideBar': foo_bar,
})
return response

Utilising the header value

response['HX-Trigger'] = json.dumps({
'ticketCounterHasChanged': '-',
'showToast': 'I am a toaster message!',
})
document.body.addEventListener("showToast", function (e) {
M.toast({html: e.detail.value});
});
Photo by Seriously Low Carb on Unsplash

Drawbacks

Wrap-up

--

--

Web development, technology, agility, creativity, UX and a healthy working environment  — We write about all the exciting things we do at work. https://ambient-innovation.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ronny Vedrilla

Tech Evangelist and Senior Developer at Ambient in Cologne, Germany.