Skip to main content

How to Build HTMX Pages with the Template DSL

In this guide, we build a small server-rendered page with htmx: the page has a button that fetches an HTML fragment from the server and swaps it into the page, without a full page reload and without writing any JavaScript. We write the page with the ZIO HTTP template DSL, add the htmx attributes with the zio-http-htmx module, and serve both the page and the fragment from the same routes.

We start with one button and its htmx attributes, put it into a full page, and then write the two handlers: one that returns the page and one that returns the fragment.

The Problem​

htmx is driven by HTML attributes such as hx-get and hx-target. The template DSL in zio.http.template has helpers for standard attributes like idAttr and srcAttr, but not for htmx attributes, so without the zio-http-htmx module you write each one by name as a string:

import zio.http.template._

val loadOrders: Html =
button(
Dom.attr("hx-get", "/orders"),
Dom.attr("hx-taget", "#orders"),
Dom.attr("hx-swap", "innerHTML"),
"Load orders",
)

This compiles, but the second attribute is misspelled. htmx ignores attributes it does not know, so the button still sends its request, and the response replaces the button's own content instead of the #orders element. Nothing in the build points at the typo.

The zio-http-htmx module defines one Scala value per htmx attribute, so a misspelled attribute name is a compile error.

Prerequisites​

Add ZIO HTTP and the htmx module to your build.sbt:

// ZIO HTTP server and client, including the template DSL
libraryDependencies += "dev.zio" %% "zio-http" % "3.12.0"

// htmx attributes for the template DSL
libraryDependencies += "dev.zio" %% "zio-http-htmx" % "3.12.0"

The examples in this guide use these imports:

import zio._

import zio.http._
import zio.http.htmx._
import zio.http.template._

import zio.http.htmx._ brings every htmx attribute into scope. Each one is named after its htmx attribute in camel case with an Attr suffix: hx-get is hxGetAttr, hx-target is hxTargetAttr, and hx-swap-oob is hxSwapOobAttr.

The htmx attributes are values of the zio.http.template DSL, described in the Template reference. They do not work with the zio.http.template2 DSL of the Template DSL reference. This guide assumes you know how to define routes and start a server.

Adding htmx Attributes to an Element​

An htmx attribute is applied like any other attribute of the template DSL: assign it a value with := and pass it to the element. This button asks htmx to send GET /orders when it is clicked, and to put the response inside the element with the ID orders:

val loadOrdersButton: Html =
button(
hxGetAttr := "/orders",
hxTargetAttr := "#orders",
hxSwapAttr := "innerHTML",
"Load orders",
)

Rendering the button with encode shows the htmx attributes in the HTML:

println(loadOrdersButton.encode)
// <button hx-get="/orders" hx-target="#orders" hx-swap="innerHTML">Load orders</button>

Each attribute does one job:

  • hxGetAttr sets the URL that htmx sends a GET request to. A button sends it when it is clicked.
  • hxTargetAttr takes a CSS selector for the element that receives the response. Without it, htmx swaps the response into the button itself.
  • hxSwapAttr says how the response is inserted. innerHTML replaces the target's content and keeps the target element; outerHTML replaces the whole target element.

Every attribute also has an apply method, so hxGetAttr("/orders") is the same as hxGetAttr := "/orders".

Rendering the Page​

The page loads the htmx script in its head and contains the button and the empty target element. Here we load htmx 2.0.4 from the unpkg CDN:

val page: Html =
html(
head(
title("Orders"),
script(srcAttr := "https://unpkg.com/htmx.org@2.0.4"),
),
body(
h1("Orders"),
loadOrdersButton,
div(idAttr := "orders", "No orders loaded yet."),
),
)

The div with idAttr := "orders" is the element that hxTargetAttr := "#orders" points at. Its text is shown until the orders are loaded.

The fragment is the HTML that replaces the content of that div. It is an ordinary Html value, not a full page, so it has no html or body element:

def orderList(orders: List[String]): Html =
ul(orders.map(order => li(order)))

println(orderList(List("order-1", "order-2")).encode)
// <ul><li>order-1</li><li>order-2</li></ul>

Serving the Page and the Fragment​

Both the page and the fragment are served as HTML with Response.html. The route for /orders is an ordinary route; only the browser treats its response differently, because htmx sent the request:

val routes: Routes[Any, Response] =
Routes(
Method.GET / "" -> handler(Response.html(page)),
Method.GET / "orders" -> handler(Response.html(orderList(List("order-1", "order-2")))),
)

Response.html sets the content-type header to text/html and writes <!DOCTYPE html> before the rendered HTML, for the fragment as well as for the page. Here is the fragment's response, without its date header:

curl -i localhost:8080/orders
HTTP/1.1 200 OK
content-type: text/html
content-length: 56

<!DOCTYPE html><ul><li>order-1</li><li>order-2</li></ul>

When htmx swaps the fragment in, the browser's HTML parser drops the DOCTYPE declaration, so after a click the div contains only the list:

<div id="orders"><ul><li>order-1</li><li>order-2</li></ul></div>

Putting It Together​

The complete example serves the routes from the previous section on port 8080. It differs from the sections only in that it defines the button inside the page instead of in a separate loadOrdersButton value:

zio-http-example/src/main/scala/example/htmx/HtmxOrdersExample.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using dep "dev.zio::zio-http-htmx:3.12.0"
// Run from this folder: scala-cli run HtmxOrdersExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.htmx.HtmxOrdersExample"

package example.htmx

import zio._

import zio.http._
import zio.http.htmx._
import zio.http.template._

/**
* Build HTMX Pages — Putting It Together
*
* Serves an HTML page at `GET /` with a button that loads the order list from
* `GET /orders` and swaps it into the page, without a full page reload.
*/
object HtmxOrdersExample extends ZIOAppDefault {

val page: Html =
html(
head(
title("Orders"),
script(srcAttr := "https://unpkg.com/htmx.org@2.0.4"),
),
body(
h1("Orders"),
button(
hxGetAttr := "/orders",
hxTargetAttr := "#orders",
hxSwapAttr := "innerHTML",
"Load orders",
),
div(idAttr := "orders", "No orders loaded yet."),
),
)

def orderList(orders: List[String]): Html =
ul(orders.map(order => li(order)))

val routes: Routes[Any, Response] =
Routes(
Method.GET / "" -> handler(Response.html(page)),
Method.GET / "orders" -> handler(Response.html(orderList(List("order-1", "order-2")))),
)

val run = Server.serve(routes).provide(Server.default)
}

Open http://localhost:8080/ in a browser and click Load orders. The text "No orders loaded yet." is replaced by the list of orders, and the page itself is not reloaded: the browser's network panel shows one request to /orders and no new request for /.

Running the Examples​

The complete example is in zio-http-example/src/main/scala/example/htmx/. Run it from that folder with scala-cli run HtmxOrdersExample.scala, or from the repository root with sbt "zioHttpExample/runMain example.htmx.HtmxOrdersExample".

Going Further​

  • The module has attributes for the other HTTP methods (hxPostAttr, hxPutAttr, hxPatchAttr, hxDeleteAttr), for choosing the event that sends the request (hxTriggerAttr), and for updating several parts of the page from one response (hxSwapOobAttr). Each renders the htmx attribute of the same name; the htmx reference describes what each one does.
  • The Template reference covers the rest of the zio.http.template DSL, including how to compose Html values into reusable components.
  • For updates that the server pushes to the page instead of request-and-swap, see How to Push Live Updates to the Browser, which uses server-sent events and WebSockets, and Building a Real-time Chat with Datastar.