(no title)
wtatum | 4 years ago
From TFA, they use the example POST /search where a snippet of HTML is returned from the /search call and is injected into the page. What would the backend look like? Presumably you still want HTML templating and component-based design instead of regressing to hand building the response, but what frameworks/packages/utilities exist in that space that don't assume they are rendering a complete page?
In particular, "whole app" frameworks like NextJS or SvelteKit are automatically mapping URLs onto a root component that is automatically decorated with all the chrome needed to make it a complete page. Is the approach to just overload those root page components and take all the chrome away to get a partial document in the response?
recursivedoubts|4 years ago
htmx includes headers, `HX-Request` which will be true if the request is an htmx request, and `HX-Target` that will be the id of the target element, if any, that allow you to modify your response as needed on the server side. This is very common: you have a single URL that satisfies both the htmx and non-htmx request (e.g. /search) and in the htmx case, you don't render the surrounding layout, but in the "normal" case you do.
If a server side option isn't available or is inconvenient, you can instead use the client-side attribute `hx-select` to select a bit of the HTML from the response for inclusion in the DOM.
Induane|4 years ago
For example I have a form that's something like
form_partial.html: partial form template: <form hx-post="{{ request.path }}" hx-swap="outerHTML" hx-encoding='multipart/form-data' hx-target="this"> {% csrftoken %} ... some other form stuff from django </form>
form.html: A normal page that includes that form: {% extends core.html %} {% include partial_form.html %}
Then in the controller code I choose whether to render the entire page (form.html) or a partial page (partial_form.html) depending on the presence of the htmx headers.
So the full load might look something like:
1. Visit mysite/coolform 2. Server renders whole page 3. Browser submits form data 4. If the form is invalid, return only the partial form, swapping the forms html and if the form IS valid, return a redirect
Another cool thing (checkout hx-boost ) about htmx is that even if you return a whole page you can actually still avoid a full page reload and only swap out the body component. So even though you're returning a few extra bytes the site isn't re-executing the entire JavaScript bundle every time you navigate to a new page.