Repository navigation
HTMX
hime ships opt-in helpers for htmx, so an app can feel like
a SPA — navigation without full reloads, partial updates, inline form
validation — while staying 100% server-rendered with Go's html/template.
No client build step, no client runtime beyond htmx itself.
Three pure predicates read the htmx request headers (they never touch the response):
-
ctx.IsHTMX()— the request came from htmx (HX-Request) -
ctx.IsBoosted()— it came fromhx-boostnavigation (HX-Boosted) -
ctx.WantsPartial()— the handler may answer with a fragment: an htmx request that is not boosted and not a history restore (both need full documents)
A view's fragments are the {{block}}/{{define}} templates it already has.
Address one with #:
ctx.View("settings#form", data) // render only the "form" block
ctx.ViewPartial("settings", "content", data) // fragment when WantsPartial, full page otherwise# is reserved: registering a template or component name containing it panics.
Fragments render through the same minify and ETag pipeline
as full pages.
One template set serves everything — full pages for browsers, deep links, the back button, and JS-off clients; fragments for htmx:
<!-- layout.tmpl -->
{{define "root"}}
<body hx-boost="true">
<nav>
<a href="{{route "settings"}}" {{if .Ctx.IsRoute "settings"}}class="active"{{end}}>Settings</a>
</nav>
{{template "body" .}}
</body>
{{end}}
<!-- settings.tmpl -->
{{define "body"}}
{{block "content" .}}
<!-- ... -->
{{end}}
{{end}}func settings(ctx *hime.Context) error {
return ctx.ViewPartial("settings", "content", newData(ctx))
}Pass ctx (or a struct embedding it) as view data to use the predicates and
IsRoute inside templates.
Keep navigation hx-boost-only: boosted requests get the full page, so the
nav (and its active state) always re-renders. If you swap a #content div and
push a URL instead, the nav goes stale — out-of-band swap it (below).
htmx follows a normal 3xx inside its XHR and swaps the target page into the
fragment — usually not what you want. Turn on:
app.HTMXAwareRedirect = trueand the whole redirect family (Redirect, RedirectTo, RedirectToGet,
RedirectBack, SafeRedirect, ...) answers partial htmx requests with
HX-Redirect + 204 — a clean client-side navigation — while plain and
boosted requests keep their normal 302/303. Post/redirect/get with
flash messages works unchanged over htmx.
ctx.HTMXRedirect(url) stays for explicit one-off use, and ctx.HTMXRefresh()
forces a full reload.
Re-render just the form on a validation error — FormState keeps the
submitted values and field errors:
func save(ctx *hime.Context) error {
f := ctx.FormState()
if ctx.PostFormValueTrimSpace("email") == "" {
f.AddError("email", "required")
return ctx.Status(422).ViewPartial("settings", "form", newData(ctx))
}
// ... save ...
ctx.AddFlash("success", "Saved!")
return ctx.RedirectToGet()
}htmx does not swap 422 responses by default — allow it once (order matters,
first match wins):
<meta name="htmx-config" content='{"responseHandling":[{"code":"422","swap":true},{"code":"204","swap":false},{"code":"[23]..","swap":true},{"code":"[45]..","swap":false,"error":true}]}'>Chainable helpers over the HX-* response headers; they compose with the
render methods.
ctx.HTMXPushURL("/items", ctx.Param("page", 2)) // push a URL into history
ctx.HTMXReplaceURL("/items") // replace the current entry
ctx.HTMXNoPush() // HX-Push-Url: false
ctx.HTMXRetarget("#list") // override where htmx swaps
ctx.HTMXReswap("outerHTML") // override how htmx swaps
ctx.HTMXReselect("#main") // select a subset of the responsefunc delete(ctx *hime.Context) error {
// ... delete the item ...
return ctx.HTMXRetarget("#list").HTMXReswap("outerHTML").Component("list", items)
}ctx.HTMXLocation("/dashboard") performs a client-side soft navigation
(HX-Location + 204) — the follow-up GET arrives as a plain htmx request, so
the target handler must render the right fragment. Prefer HTMXRedirect (or
app.HTMXAwareRedirect) unless you know you want this.
ctx.HTMXTrigger fires client-side events via the HX-Trigger header.
Repeated calls merge into one header; HTMXTriggerAfterSwap and
HTMXTriggerAfterSettle do the same for the other timings. Merged events
serialize in alphabetical (not call) order.
ctx.HTMXTrigger("itemAdded") // HX-Trigger: itemAdded
ctx.HTMXTrigger("itemAdded", map[string]any{"id": 7}) // HX-Trigger: {"itemAdded":{"id":7}}
ctx.HTMXTrigger("a").HTMXTrigger("b") // HX-Trigger: a, bOOB is a template pattern, not an API: put a conditional hx-swap-oob on an
element that carries an id, inside the fragment you render. On a full-page
render the same element is just part of the page.
{{block "content" .}}
<div id="flash" {{if .Ctx.WantsPartial}}hx-swap-oob="true"{{end}}>
{{range .Flash.success}}<p class="ok">{{.}}</p>{{end}}
</div>
<!-- ... rest of the fragment ... -->
{{end}}The attribute must be conditional — a boosted full-body swap would otherwise
rip the element out of the page flow. For composing responses from several
rendered components, ctx.RenderComponentToString still works — see
Component.
hime never sets cache headers for you:
-
ctx.NoCache()(chainable) setsCache-Control: no-store— the easy path for authenticated apps; responses served with it need nothing else. - If htmx-branching responses are cacheable (a CDN in front,
app.ETagrevalidation, or noCache-Controlat all — browsers may heuristically cache those), callctx.VaryHTMX()(chainable). It appendsVary: HX-Request, HX-Boosted, HX-History-Restore-Requestso caches never mix full pages, boosted pages, and fragments. Branching onHX-Targettoo? Addctx.AddHeader("Vary", "HX-Target")as well.
-
HX-*request headers are client-controlled. Use them to pick the framing (fragment vs full page) only — never for authorization, and never to skip CSRF checks.
Set SameSite=Lax (or Strict) explicitly on your session cookie and
never mutate state on GET — that alone stops classic cross-site form CSRF in
modern browsers. (Explicit matters: browser default-Lax behavior is not
uniform and Chrome's default carries a POST grace window for fresh cookies.)
The remaining gap is same-site-but-cross-origin attackers (a subdomain takeover, user content hosted on a subdomain). Go 1.25's standard library covers it — hime adds nothing because it composes directly:
cop := http.NewCrossOriginProtection()
cop.AddInsecureBypassPattern("/webhook/") // exempt endpoints that accept cross-site POSTs
app.Handler(cop.Handler(mux))http.CrossOriginProtection
rejects non-safe cross-origin browser requests using Sec-Fetch-Site, falling
back to comparing Origin against Host for older browsers; requests with
neither header (non-browser clients, webhooks) pass. Use AddTrustedOrigin
for legitimate cross-origin callers (e.g. an SSO callback) and
SetDenyHandler to customize the 403.
For a per-handler decision instead of a wrapper, call cop.Check(ctx.Request)
inside the handler.
If you use token middleware anyway, wire it with hx-headers, e.g.
<body hx-headers='{"X-CSRF-Token": "{{.Token}}"}'>, and prefer per-session
tokens (or set hx-history="false"): htmx snapshots pages into localStorage,
so per-request tokens leak into the snapshot.