Skip to the page
Kiln / Pages that change in place

Start here01

The language02

Programs and the world03

Kiln04

04 Kiln / 03

Pages that change in place

Parts of a page that update without a reload, with no JavaScript of your own.

Often only one part of a page needs to change, like a todo item when it's marked done. The page can ask the server for that piece of HTML alone, and put it in place. htmx does that in the browser, from attributes on your HTML. On the server, any template can be the whole response, so a handler gives the piece.

One piece, one template

Here a todo item is a template of its own. Its button carries the attributes that tell htmx where to post, and which element to swap for what comes back:

template
# views/todo.och: one item, on its own.
import "../models"

takes
  todo: Todo
end

li
  id: "todo-#{todo.id}"

  todo.title

  button "Done"
    hx-post: "/todos/#{todo.id}/done"
    hx-target: "#todo-#{todo.id}"
    hx-swap: "outerHTML"
  end
end

The handler for that route finishes the todo, and gives the same template as the whole response:

hem
static def done(request: Request, id: Int): Response!
  const todo = try Todos.finish(id)
  return Response.html(todo_view.render(todo: todo), status: 200)
end

When someone presses the button on item 42:

  1. 1htmx posts to /todos/42/done.
  2. 2The handler finishes the todo, and answers with its li, rendered by views/todo.och.
  3. 3htmx swaps in the li that comes back, in place of #todo-42. The rest of the page stays as it was.

Loading htmx

The page loads htmx once, like any script: a script with src: "/assets/htmx.min.js", with the file served by Route.files.

Working without JavaScript too

The same button can also work without JavaScript, as a form that posts and reloads the page. Then the handler asks who sent the request: Htmx.asked(request) is true when htmx did (see requests). htmx gets the piece. A browser on its own gets the whole page, or a redirect to it. So does htmx bringing a page back from its history (going back to a page it no longer keeps), so Htmx.asked(request) is false then.

htmx-asked.hem
import "@kiln"

const htmx = new Request(
  method: "POST",
  path: "/todos/42/done",
  query: "",
  headers: {"hx-request": "true"},
  body: "",
)

print(Htmx.asked(htmx)) # prints true