How re-rendering with HTMX works
In goal 1, our server sent back an empty response. HTMX had nothing to put on the page, so the page didn’t change.
This time, we want the page to change. The plan is:
- The user clicks a checkbox.
- HTMX sends a
POSTrequest to the server. - The server saves the change, then renders the todo item’s partial and sends back the HTML.
- HTMX takes that HTML and swaps it into the page, in place of the old todo item.
The server sends back HTML
This is the big idea behind HTMX: the server sends back HTML, not data.
Our todo item already has its own small template: todo/partials/todo_item.html. The home page uses it to render every item in the list. Now our toggle view can use the same template to render just one item.
That means the logic for how a todo item looks lives in one place. If the item is done, the template crosses it out. We don’t have to repeat that logic in JavaScript.
HTMX puts the HTML on the page
We need to tell HTMX two things:
- Where the HTML should go. We use
hx-targetfor this. - How it should go there. We use
hx-swapfor this.
Where: hx-target
By default, HTMX puts the response into the element that made the request. For us, that’s the checkbox. That’s not what we want. We want to replace the whole todo item.
So we give each todo item a unique id, and point hx-target at it:
<div id="todo-item-3">
<input type="checkbox" hx-post="/todo/3/toggle/" hx-target="#todo-item-3" ...>
...
</div>#todo-item-3 is a CSS selector. It means “the element with the id todo-item-3”.
How: hx-swap
By default, HTMX uses innerHTML. That replaces the contents of the target, but keeps the target itself.
Our partial renders the whole todo item, including its outer <div>. If we used innerHTML, we’d end up with a todo item <div> inside another todo item <div>.
So we use hx-swap="outerHTML". That replaces the whole target element with the response.
<input type="checkbox"
hx-post="/todo/3/toggle/"
hx-target="#todo-item-3"
hx-swap="outerHTML">