Swapping

Swapping is the process of swapping out the content of an element with another element.

This is the primary way htmgo allows you to add interactivity to your website through htmx.

The swapping examples below utilize hx-swap-oob behind the scenes to swap out the content of an element.

Example: A simple counter

Copy
 1func CounterPartial(ctx *h.RequestContext) *h.Partial {
 2	count, _ := strconv.ParseInt(ctx.FormValue("count"), 10, 64)
 3
 4	count++
 5
 6	return h.SwapManyPartial(
 7		ctx,
 8		CounterForm(int(count)),
 9		h.ElementIf(count > 10, SubmitButton("New record!")),
10	)
11}
12
13func CounterForm(count int) *h.Element {
14	return h.Form(
15		h.Id("counter-form"),
16		h.PostPartial(CounterPartial),
17		h.Input(
18			"text",
19			h.Class("hidden"),
20			h.Value(count),
21			h.Name("count"),
22		),
23		h.P(
24			h.Id("counter"),
25          	h.Name("count"),
26			h.TextF("Count: %d", count),
27		),
28		h.Button(
29			h.Type("submit"),
30			h.Text("Increment"),
31		),
32	)
33}

In this example, when the form is submitted, an HTTP POST will be sent to the server and call CounterPartial.

CounterPartial will then update the count and return it back to the client via h.SwapManyPartial.

The h.SwapManyPartial function is a helper function that allows you to swap out multiple elements on the page.

All the routing is handled behind the scenes by htmgo, so you can reference partials directly by their function reference,

instead of having to wire up routes for each partial.

Sometimes you may need to pass additional information when calling the partial, such as an id of the current entity you are working with.

This can be done by like so:

Example: Getting the http path to the partial with extra qs parameters

Copy
1func MyComponent() *h.Element {
2	return h.Div(
3		h.GetPartialPathWithQs(
4			CounterPartial,
5			h.NewQs("count", count),
6		),
7	)
8}

Example: Posting to the partial path on blur

Copy
1func MyComponent() *h.Element {
2	path := h.GetPartialPath(CounterPartial)
3	return h.Input(
4		h.Post(path, hx.BlurEvent),
5	)
6}

Note: if your swapping is not working as expected, make sure the element you are swapping has an id and it matches. For further details on how oob works behind the scenes, see the hx-swap-oob docs.