Kiln / Pages that change in place
Start here01
The language02
- 01The basics
- 02Values and numbers
- 03Variables
- 04Calls and expressions
- 05Conditions and loops
- 06Strings
- 07Arrays and hashes
- 08Classes and records
- 09Traits and enums
- 10Blocks
- 11Methods
- 12Imports and exports
- 13Foreign files
- 14Failures
Programs and the world03
- 01Files, input and output
- 02JSON, time, URLs and random numbers
- 03Html and forms
- 04Templates: Ochre
- 05Built-in methods
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:
# 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
endThe handler for that route finishes the todo, and gives the same template as the whole response:
static def done(request: Request, id: Int): Response!
const todo = try Todos.finish(id)
return Response.html(todo_view.render(todo: todo), status: 200)
endWhen someone presses the button on item 42:
- 1htmx posts to
/todos/42/done. - 2The handler finishes the todo, and answers with its
li, rendered byviews/todo.och. - 3htmx swaps in the
lithat 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.
import "@kiln"
const htmx = new Request(
method: "POST",
path: "/todos/42/done",
query: "",
headers: {"hx-request": "true"},
body: "",
)
print(Htmx.asked(htmx)) # prints true