r/webdev • u/Meercrow • 1d ago
Discussion Using HTMX alongside any templating engine, how do you deal with the mess that happens when you need to handle both an hx-request and a normal browser request in every handler?
I am using askama (uses structs instead of a HashMap for template data) with htmx and was able to make pages out of fragments easily by doing:
{% extends "base.html" %}
{% block title %}Not Found{% endblock title %}
{% block content %}
{% include "fragments/not_found.html" %}
{% endblock content %}as in every page being a file that just includes the corresponding fragments, and this worked very well for a long time but made my handlers look like (simplified):
async |HxRequest(hx): HxRequest| {
if hx {
NotFound // return fragment if this is an htmx request
} else {
NotFoundPage // return full page for normal requests
}
}A few lines of code added to every single handler. This is also very much manageable. But later
I wanted some notifications to be hx-partial added to any request which would target a #toasts in base.html and had to somehow make it work with full page loads as well.
With my current solution, fragments carry errors as partials, while for pages I added a block toasts where I add errors, making every page struct have that field and messing with every route handler again.
How are others dealing with this?