r/webdev • u/Meercrow • 8h 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?
2
u/Agent360dk 8h ago
For the toasts specifically, htmx has a built in way: send an HX-Trigger response header like {"toast":{"msg":"Saved","level":"ok"}} and listen for it with one document.body.addEventListener('toast', ...) in base.html. Then partial responses never carry toast markup at all. For full page loads (redirects after a form post, say) stash the message in a short lived flash cookie or session value, and have base.html render it once and clear it. A tower of per-page toast fields goes away because the handler only calls something like flash(msg) and a middleware picks the right transport depending on whether it's an htmx request.
5
u/Rextkrl 8h ago
the pattern that killed most of the branching for me is making the template do it instead of the handler. htmx always sends the HX-Request header, so pass that flag into your render context and let base.html decide: when it's an htmx request render just the block, when it's not render the block inside the layout. every handler then returns one template either way and the if hx branch disappears from the code. fragments stay fragments, pages are just the same fragment wrapped in the layout. the error half is worse than the routing half imo, one global toast target plus a single error partial beats per-page error blocks
6
u/SpeedCola 8h ago
This may not be immediately helpful but as my web pages complexity grew I too found myself struggling to do what I wanted without tons of confusing workarounds. I decided to just learn JS and I never looked back.
For your case specifically, toasts are a natural fit for a few lines of JS. Send them in a response header and have a small listener show them, so your page templates never need to know about them.
1
u/TheOfficeWM 7h ago
I handle it with one wrapper that checks for the hx-request header and returns a fragment, full layout otherwise. The trade-off is every handler has to remember the wrapper exists, but it beats duplicating handlers.
1
u/_uxi 8h ago
You check for the HTTP header on the request. Have one controller return either the full page or the partial. Make two templates, one partial and one full page. The full page uses includes wherever the partial occurs. No redundancy, no repeating. One code path for both. Exactly like you’re already doing.
1
u/miles-88 7h ago
With typed templates like Askama, the cleanest way I've found to avoid touching every struct and handler is pushing both concerns into a small response wrapper or middleware:
1
u/ZestycloseStrain8482 7h ago
Small thing: 'managable' takes an e, it's manageable.
1
u/krileon 7h ago
I treat HTMX requests same as I would API requests. It's segregated entirely. So for example...
/api/post/1
/post/1
The API endpoint is for HTMX and is always a partial. The non-API endpoint is the full response. They'll output their respective HTML as needed instead of trying to handle both scenarios in a single route.
1
u/satoshi_builder 6h ago
The part that would bother me most is the toasts field landing on every page struct. Did you try a shared wrapper struct for the common fields, or does askama make that more awkward than it looks?
1
u/RiceEvening4211 3h ago
For the nested case, let HX-Target pick the layer instead of branching in every handler. One helper maps the target id to the fragment to render: a table request returns just CertTable, a container request returns CertContainer with the table inside, and a plain request wraps whichever fragment in the layout. Handlers then just return a fragment. For toasts, use the HX-Trigger header approach others mentioned — one listener in base.html plus a flash cookie for full page loads keeps that field out of every page struct.
1
u/Comfortable_Job8847 7h ago
i think you shouldnt do that. instead let your server send data not just html and have client-rendered widgets which process it i guess. that way you dont have to deal with demo tech like htmx so much and youll have an easier time i think. so you wont have to reinvent it in html templates. and you dont need such complicated endpoints either. its much better. less complicated code. you maybe could even test the widgets independently. no coupling.
0
u/[deleted] 7h ago
[removed] — view removed comment