I have Askama page templates that include the same fragments I return for HTMX requests, but checking the request in every handler is getting repetitive. Toast notifications are also awkward because they need to work for both partial responses and full page loads. How would you structure this?
How do you handle full pages and HTMX fragments with Askama?
Answers
Keep the fragment and page templates, but move the request check into a shared response helper. The handler builds the fragment data, then the helper returns either the rendered fragment or a layout containing it.
That gives you one place to deal with the HX-Request header and common layout data such as notifications. If you insert rendered HTML into a layout with a safe filter, only mark trusted, already escaped template output as safe. Don't apply it directly to user input.
Reply to this answer
Another option is to pass an HTMX flag into the template context and let the template decide whether to render the layout around the content. Then the handler returns one template type instead of choosing between two.
With Askama's typed contexts, a shared context struct can hold the flag and common page fields. It won't make those fields disappear, but it can keep them together instead of repeating them individually.
Reply to this answer
For toasts, separate the notification from the HTML response. An HTMX response can send an HX-Trigger header with the message and level, and a small JavaScript listener can display it.
For a normal page load, use a short-lived flash cookie or session value and render the message in the layout. That's still two delivery paths, but the individual fragment templates don't need toast markup.
Briefly:
That sounds useful for form submissions too. The full-page path would need to carry the flash message across a redirect.
Reply to this answer
You can also split the routes. Have one endpoint that always returns a full page and another that always returns the fragment. Share the data-fetching logic and include the fragment in the page template, but keep the response types predictable.
More routes, less request-specific branching. Whether that's worth it depends on how many fragments have their own useful endpoints.
Reply to this answer
If the real headache is nested fragments rather than just page versus partial, a helper can map known HX-Target values to the appropriate template layer. A table target might get the table, while a container target gets the surrounding section too.
Keep the mapping explicit and handle missing or unexpected targets. A normal browser request can still use the full layout.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Margo T:
The trade-off is that handlers still need to use the wrapper, and pages with different layouts or extra metadata may need a little more configuration.