Documentation menu

Swapping

An htmx request can replace part of a page with HTML from a partial. Use an out-of-band swap to update several elements from one response.

The counter form uses hx-swap-oob to replace the form and its separate status message by ID.

Add these functions under pages/ in the starter project and import strconv.

Copy
 1func CounterPage(ctx *h.RequestContext) *h.Page {
 2	return RootPage(
 3		h.Div(CounterForm(0), CounterStatus(0)),
 4	)
 5}
 6
 7func CounterPartial(ctx *h.RequestContext) *h.Partial {
 8	count, _ := strconv.Atoi(ctx.FormValue("count"))
 9	count++
10	return h.SwapManyPartial(ctx, CounterForm(count), CounterStatus(count))
11}
12
13func CounterForm(count int) *h.Element {
14	return h.Form(
15		h.Id("counter-form"),
16		h.PostPartial(CounterPartial),
17		h.NoSwap(),
18		h.Input("hidden", h.Name("count"), h.Value(count)),
19		h.Button(h.Type("submit"), h.Text("Increment")),
20	)
21}
22
23func CounterStatus(count int) *h.Element {
24	return h.P(
25		h.Id("counter-status"),
26		h.TextF("Count: %d", count),
27	)
28}

Submitting the form sends a POST to CounterPartial. h.NoSwap suppresses the main swap. h.SwapManyPartial marks both returned elements for out-of-band swaps. Give each replacement the same ID as the element already in the page.

Use h.GetPartialPathWithQs to construct a partial URL with query parameters. Use ctx.QueryParam to read them in the receiving handler.

Copy
1func CounterPath(count int) string {
2	return h.GetPartialPathWithQs(
3		CounterPartial,
4		h.NewQs("count", strconv.Itoa(count)),
5	)
6}

Pass a trigger such as hx.BlurEvent to h.PostPartial to submit when an input loses focus.

Copy
1func CounterInput(count int) *h.Element {
2	return h.Input("number",
3		h.Name("count"),
4		h.Value(count),
5		h.PostPartial(CounterPartial, hx.BlurEvent),
6		h.NoSwap(),
7	)
8}