valfz

Server-rendered apps with Go, templ and HTMX

Interaction patterns

Active search with debounce, editing in place, delete with confirmation, a counter updated out of band, and a little Alpine.js.

lesson
07 of 08
read
18 min

Three htmx interactions are in place. This lesson adds the ones that make the application feel finished: search that runs as you type, editing a link where it stands, deleting with a confirmation, and an unread counter that every change keeps correct. One piece of state turns out not to need the server at all, and that is where Alpine.js comes in.

Search as you type

The server side of search has existed since lesson 2. Active search is a change to three attributes on the form:

links.templ
templ SearchForm(f Filter) {
	<form
		id="search"
		action="/links"
		method="get"
		hx-get="/links"
		hx-trigger="input delay:300ms, submit"
		hx-sync="this:replace"
		hx-target="#links"
		hx-swap="outerHTML"
		hx-replace-url="true"
	>
		<input type="search" name="q" value={ f.Query } placeholder="Search" aria-label="Search"/>
		<select name="filter" aria-label="Show">
			<option value="all">All</option>
			<option value="unread" selected?={ f.Status == "unread" }>Unread</option>
			<option value="read" selected?={ f.Status == "read" }>Read</option>
		</select>
		<button type="submit">Search</button>
	</form>
}

input events bubble up from the text field and from the dropdown. delay:300ms restarts a timer on every event and sends the request when the timer runs out, which is a debounce. In the browser, typing three letters 80 ms apart produced one request, about 300 ms after the last key. submit stays in the list so that Enter searches at once and the form still works without scripts.

hx-sync="this:replace" aborts a request that is still in flight when the form starts a new one, so a slow early response cannot overwrite a later one. With an artificial delay in the handler, the browser’s network panel showed the first request as canceled the moment the second went out.

hx-replace-url takes the place of hx-push-url. With push, every pause in typing would add a history entry. Replacing keeps the address bar accurate, and a reload still shows the same results, without burying the previous page under partial queries.

Shared attributes

Each list item is about to have three controls that all want the same target and swap. htmx 4 does not inherit attributes from parent elements unless asked. The :inherited modifier asks:

links.templ
templ LinkList(links []Link) {
	<ul id="links" hx-target:inherited="closest li" hx-swap:inherited="outerHTML">
		for _, l := range links {
			@LinkItem(l)
		}
		<li class="empty">Nothing here yet.</li>
	</ul>
}

templ LinkItem(l Link) {
	<li
		id={ fmt.Sprintf("link-%d", l.ID) }
		if l.Read {
			class="read"
		}
	>
		<a href={ l.URL }>{ l.Title }</a>
		<small>{ host(l.URL) }, { l.CreatedAt.Format("Jan 2") }</small>
		if l.Note != "" {
			<p>{ l.Note }</p>
		}
		<div class="actions">
			<form action={ linkPath(l.ID) + "/toggle" } method="post" hx-post={ linkPath(l.ID) + "/toggle" }>
				<button type="submit">
					if l.Read {
						Mark unread
					} else {
						Mark read
					}
				</button>
			</form>
			<button type="button" hx-get={ linkPath(l.ID) + "/edit" }>Edit</button>
			<button type="button" hx-delete={ linkPath(l.ID) } hx-swap="delete" hx-confirm="Delete this link?">Delete</button>
		</div>
	</li>
}

func linkPath(id int64) string {
	return fmt.Sprintf("/links/%d", id)
}

hx-target:inherited="closest li" on the list applies to every element inside it that makes a request, and the selector is resolved from that element. Each control now states only what is specific to it.

Delete with confirmation

The Delete button sends a DELETE request after hx-confirm has shown the browser’s confirmation dialog and the user has accepted. hx-swap="delete" overrides the inherited swap and removes the target whatever the response contains.

The confirmation text is a constant on purpose. It would be friendlier to name the link, but htmx runs the value of hx-confirm as JavaScript when it starts with js: (set by hand in the browser, such a value executed and no dialog appeared). A title is user input, and templ’s escaping knows nothing about that convention. Keep user input out of attributes that can be evaluated.

Edit in place

The Edit button fetches a replacement for its list item: the same <li>, containing a form.

links.templ
// EditForm renders a list item in edit mode.
templ EditForm(id int64, f LinkForm) {
	<li id={ fmt.Sprintf("link-%d", id) } class="editing">
		<form hx-put={ linkPath(id) }>
			@LinkFields(f)
			<button type="submit">Save</button>
			<button type="button" hx-get={ linkPath(id) }>Cancel</button>
		</form>
	</li>
}

The three inputs are the ones the add form has, so they move into a component both forms use. Replace the labels in AddForm with @LinkFields(f), and add unicode/utf8 to the imports of links.templ:

links.templ
// LinkFields renders the inputs shared by the add form and the edit form.
templ LinkFields(f LinkForm) {
	<label>
		URL
		<input type="url" name="url" value={ f.URL } required aria-invalid?={ f.Errors["url"] != "" }/>
		@fieldError(f.Errors["url"])
	</label>
	<label>
		Title
		<input type="text" name="title" value={ f.Title } required aria-invalid?={ f.Errors["title"] != "" }/>
		@fieldError(f.Errors["title"])
	</label>
	<label x-data={ templ.JSONString(map[string]int{"used": utf8.RuneCountInString(f.Note), "max": maxNoteLen}) }>
		Note
		<textarea
			name="note"
			rows="2"
			aria-invalid?={ f.Errors["note"] != "" }
			x-on:input="used = Array.from($el.value).length"
		>{ f.Note }</textarea>
		<small x-text="max - used" x-bind:class="used > max ? 'error' : ''"></small>
		@fieldError(f.Errors["note"])
	</label>
}

The x- attributes on the note field are Alpine and are explained at the end. Two routes and two handlers complete the round trip:

routes.go
	mux.HandleFunc("GET /links/{id}/edit", a.editLink)
	mux.HandleFunc("PUT /links/{id}", a.updateLink)
handlers.go
func (a *app) editLink(w http.ResponseWriter, r *http.Request) {
	id, ok := pathID(r)
	if !ok {
		a.notFound(w, r)
		return
	}
	l, err := a.store.Get(r.Context(), id)
	if err != nil {
		a.storeError(w, r, err)
		return
	}
	form := LinkForm{URL: l.URL, Title: l.Title, Note: l.Note}
	a.render(w, r, http.StatusOK, EditForm(l.ID, form))
}

func (a *app) updateLink(w http.ResponseWriter, r *http.Request) {
	id, ok := pathID(r)
	if !ok {
		a.notFound(w, r)
		return
	}
	form, ok := a.readLinkForm(w, r)
	if !ok {
		return
	}
	if !form.Validate() {
		a.render(w, r, http.StatusUnprocessableEntity, EditForm(id, form))
		return
	}

	l, err := a.store.Update(r.Context(), id, form.URL, form.Title, form.Note)
	if errors.Is(err, ErrDuplicate) {
		form.Errors["url"] = "This link is already on the list."
		a.render(w, r, http.StatusUnprocessableEntity, EditForm(id, form))
		return
	}
	if err != nil {
		a.storeError(w, r, err)
		return
	}
	a.render(w, r, http.StatusOK, LinkItem(l))
}
store.go
func (s *Store) Update(ctx context.Context, id int64, url, title, note string) (Link, error) {
	row := s.db.QueryRowContext(ctx, `
		UPDATE links SET url = ?, title = ?, note = ?
		WHERE id = ?
		RETURNING `+linkColumns,
		url, title, note, id)
	l, err := scanLink(row)
	if isUniqueViolation(err) {
		return Link{}, ErrDuplicate
	}
	return found(l, err)
}

Save sends a PUT and gets the list item back in view mode. Cancel fetches GET /links/{id}, the fragment route that has existed since lesson 3. A validation failure answers 422 with the edit form, and this time no hx-status is needed: the error goes to the same target as a success, and htmx 4 swaps it by default.

HTML forms cannot send PUT or DELETE, so editing and deleting need htmx. Adding, marking and searching keep working without it.

A counter, out of band

The page gets a line such as “1 unread of 2”. Adding, marking and deleting all change it, and none of them targets it. This is the case hx-swap-oob was introduced for in lesson 5.

store.go
// Stats counts all links and the unread ones.
type Stats struct {
	Total  int
	Unread int
}

func (s *Store) Stats(ctx context.Context) (Stats, error) {
	var st Stats
	err := s.db.QueryRowContext(ctx,
		`SELECT count(*), count(*) FILTER (WHERE read = 0) FROM links`).
		Scan(&st.Total, &st.Unread)
	return st, err
}
links.templ
// Counter shows how many links are unread. With oob set, htmx swaps it over
// the counter already on the page.
templ Counter(s Stats, oob bool) {
	<p
		id="counter"
		if oob {
			hx-swap-oob="true"
		}
	>
		{ s.Unread } unread of { s.Total }
	</p>
}

templ LinksPage(links []Link, f Filter, form LinkForm, stats Stats) {
	@Page("Reading list") {
		@AddForm(form, false)
		@SearchForm(f)
		@Counter(stats, false)
		@LinkList(links)
	}
}

Two helpers in handlers.go keep the handlers short:

handlers.go
// renderPage writes the whole page: the given list and form, plus the counter.
func (a *app) renderPage(w http.ResponseWriter, r *http.Request, status int, links []Link, f Filter, form LinkForm) {
	stats, err := a.store.Stats(r.Context())
	if err != nil {
		a.serverError(w, r, err)
		return
	}
	a.render(w, r, status, LinksPage(links, f, form, stats))
}

// renderWithCounter writes the given components followed by an up-to-date
// counter marked for an out-of-band swap.
func (a *app) renderWithCounter(w http.ResponseWriter, r *http.Request, status int, cs ...templ.Component) {
	stats, err := a.store.Stats(r.Context())
	if err != nil {
		a.serverError(w, r, err)
		return
	}
	cs = append(cs, Counter(stats, true))
	a.render(w, r, status, templ.Join(cs...))
}

Use them in four places. listLinks ends with a.renderPage(w, r, http.StatusOK, links, f, LinkForm{}) and invalidForm with a.renderPage(w, r, http.StatusUnprocessableEntity, links, Filter{}, form). In createLink the partial branch becomes a.renderWithCounter(w, r, http.StatusCreated, LinkItem(l), AddForm(LinkForm{}, true)), and in toggleLink it becomes a.renderWithCounter(w, r, http.StatusOK, LinkItem(l)). Deleting is the interesting one:

handlers.go
func (a *app) deleteLink(w http.ResponseWriter, r *http.Request) {
	id, ok := pathID(r)
	if !ok {
		a.notFound(w, r)
		return
	}
	if err := a.store.Delete(r.Context(), id); err != nil {
		a.storeError(w, r, err)
		return
	}
	if isPartial(r) {
		// Nothing replaces the item; the response only carries the counter.
		a.renderWithCounter(w, r, http.StatusOK)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

After templ generate and a restart, with the two links from lesson 6:

curl -s -X POST -H 'HX-Request-Type: partial' localhost:8792/links/1/toggle
<li id="link-1"><a href="https://go.dev/blog/routing-enhancements">Routing Enhancements for Go 1.22</a> <small>go.dev, Nov 29</small> <div class="actions"><form action="/links/1/toggle" method="post" hx-post="/links/1/toggle"><button type="submit">Mark read</button></form><button type="button" hx-get="/links/1/edit">Edit</button> <button type="button" hx-delete="/links/1" hx-swap="delete" hx-confirm="Delete this link?">Delete</button></div></li><p id="counter" hx-swap-oob="true">2 unread of 2</p>
curl -s -o /dev/null -d url=https://example.com/tmp -d title=Temporary localhost:8792/links
curl -i -X DELETE -H 'HX-Request-Type: partial' localhost:8792/links/3
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Date: Sat, 28 Nov 2026 22:21:41 GMT
Content-Length: 52

<p id="counter" hx-swap-oob="true">2 unread of 2</p>

The delete response consists of an out-of-band element and nothing else. Once htmx has taken that element out, nothing is left, and in that situation htmx skips the main swap and leaves the target alone. That is the second reason for hx-swap="delete": it runs regardless. The status is 200 and not 204, because htmx does not swap on a 204 at all. Tried with a 204, the row stayed on screen although the link was gone from the database.

Errors still behave. When the link is already gone, fail answers 404 with HX-Reswap: innerHTML and HX-Retarget: #flash. Those headers win over the delete swap in the markup, so the message appears and the row stays.

State that stays in the browser

The note is limited to 280 characters, and a count of what is left should follow every keystroke. Asking the server after each key would be wasteful, and nothing else on the page depends on the number. For state like this, Alpine.js adds behavior with attributes, in the same spirit as htmx. Download it next to htmx and load it with defer:

curl -sSfLo static/alpine.min.js https://cdn.jsdelivr.net/npm/alpinejs@3.17.5/dist/cdn.min.js
layout.templ
			<script src="/static/htmx.min.js"></script>
			<script src="/static/alpine.min.js" defer></script>

The note field in LinkFields, shown earlier, uses four Alpine attributes. x-data on the label declares a small state object. x-on:input recomputes used from the textarea, x-text prints what remains, and x-bind:class turns it red past the limit. Array.from counts code points, the unit the server counts with utf8.RuneCountInString.

The initial state comes from the server through templ.JSONString, which renders x-data="{&#34;max&#34;:280,&#34;used&#34;:32}" for a note of 32 characters. Alpine evaluates x-data as JavaScript, so building that value by concatenating strings would be an injection risk. Encoding it as JSON is not.

Alpine initializes elements that htmx swaps in: the count works in the edit form and in the blank add form that arrives out of band. Its state lives on the DOM node, though. When htmx replaces the node, the state goes with it, which is fine here because the server renders the starting value each time. The server also remains the authority on the limit. The counter is a convenience.

Two more rules for the stylesheet:

static/app.css
.actions { display: flex; gap: .5rem; }
.actions form { margin: 0; }

The application is complete. What remains is to prove that it works and to package it.

Exercises

  1. Let Escape cancel an edit. Give the Cancel button hx-trigger="click, keyup[key=='Escape'] from:'closest form'". A correct result: pressing Escape in any field of the edit form restores the row unchanged. Then remove the quotes around closest form and observe that Escape does nothing: an extended selector containing a space has to be quoted inside hx-trigger.
  2. Search for wal, then add a link that does not match. It is prepended to the filtered list anyway. Fix this in createLink: htmx sends the page’s address in the HX-Current-URL request header, including the q parameter that hx-replace-url put there. When the new link does not match, leave LinkItem out of the response. A correct result: the list stays as it was, while the form still resets and the counter still goes up, because a response with only out-of-band elements skips the main swap.
  3. Show that a search is running. Put <span class="htmx-indicator">Searching</span> inside the search form and add a temporary time.Sleep to listLinks. During the request the form should carry the class htmx-request and the indicator should be visible. Afterwards the class is gone and the indicator is hidden again. Remove the sleep.

keyboard

h
home
w c a
writing, courses, about
n p
next and previous lesson
j k
scroll down and up
g G
top and bottom of the page
t
switch light and dark
?
this help

shortcuts are