Documentation
¶
Overview ¶
Package htmx provides utilities for working with HTMX requests and responses.
HTMX enables developers to access AJAX, WebSockets, and Server-Sent Events directly in HTML attributes, simplifying dynamic web application development. This package offers convenient functions and constants to detect HTMX requests, send appropriate HTMX response headers, and configure rendering behavior.
Request Detection ¶
Use IsHTMX to check if an incoming HTTP request originated from an HTMX element:
import (
"github.com/dmitrymomot/forge/pkg/htmx"
"net/http"
)
func myHandler(w http.ResponseWriter, r *http.Request) {
if htmx.IsHTMX(r) {
// Handle HTMX-specific logic
}
}
Navigation and Redirects ¶
Use the Location and Redirect functions to handle navigation for both HTMX and regular HTTP requests. These functions automatically detect HTMX requests and respond appropriately:
// Simple redirect - uses HX-Redirect header for HTMX, HTTP redirect for regular requests
htmx.Redirect(w, r, "/new-page")
// Navigation with target element update
htmx.LocationTarget(w, r, "/api/users", "#user-list")
// Advanced location options with custom parameters
opts := htmx.LocationOptions{
Path: "/dashboard",
Target: "#main",
Swap: string(htmx.SwapInnerHTML),
}
htmx.LocationWithOptions(w, r, opts)
Swap Strategies ¶
The SwapStrategy type defines how content should be inserted into the target element:
- SwapInnerHTML: Replace inner HTML (default)
- SwapOuterHTML: Replace entire element
- SwapBeforeBegin: Insert before element
- SwapAfterBegin: Insert before first child
- SwapBeforeEnd: Insert after last child
- SwapAfterEnd: Insert after element
- SwapDelete: Remove the element
- SwapNone: Don't swap
Render Configuration ¶
The Config and RenderOption types provide fluent configuration for rendering components with HTMX response headers. Use NewConfig with options to build a configuration, then ApplyHeaders to set headers before writing the response:
cfg := htmx.NewConfig(
htmx.WithRetarget("#new-target"),
htmx.WithReswap(htmx.SwapOuterHTML),
htmx.WithTrigger("componentUpdated"),
)
cfg.ApplyHeaders(w)
w.WriteHeader(http.StatusOK)
// Write response body
Out-of-Band Swaps ¶
Configure out-of-band (OOB) components to render multiple elements in a single response:
cfg := htmx.NewConfig( htmx.WithOOB(sidebarComponent, footerComponent), ) // Components must include id and hx-swap-oob attributes
Response Headers ¶
The package exports constants for all HTMX response headers. Common response headers include:
- HX-Location: Client-side navigation with URL update
- HX-Redirect: Client-side redirect
- HX-Retarget: Change the target element
- HX-Reswap: Change the swap strategy
- HX-Refresh: Refresh the page
- HX-Trigger: Trigger client-side events
- HX-Push-Url: Update browser history
- HX-Replace-Url: Replace current URL
Request headers are also available as constants for inspection.
Index ¶
- Constants
- func IsHTMX(r *http.Request) bool
- func Location(w http.ResponseWriter, r *http.Request, path string)
- func LocationTarget(w http.ResponseWriter, r *http.Request, path, target string)
- func LocationWithOptions(w http.ResponseWriter, r *http.Request, opts LocationOptions)
- func Redirect(w http.ResponseWriter, r *http.Request, url string)
- func RedirectBack(w http.ResponseWriter, r *http.Request, fallback string)
- func RedirectWithStatus(w http.ResponseWriter, r *http.Request, targetURL string, status int)
- type Config
- type LocationOptions
- type RenderOption
- func WithOOB(components ...Renderable) RenderOption
- func WithPushURL(url string) RenderOption
- func WithRefresh() RenderOption
- func WithReplaceURL(url string) RenderOption
- func WithReselect(selector string) RenderOption
- func WithReswap(strategy SwapStrategy) RenderOption
- func WithRetarget(selector string) RenderOption
- func WithTrigger(events ...string) RenderOption
- func WithTriggerAfterSettle(events ...string) RenderOption
- func WithTriggerAfterSwap(events ...string) RenderOption
- type Renderable
- type SwapStrategy
Constants ¶
const ( HeaderHXLocation = "HX-Location" HeaderHXPushURL = "HX-Push-Url" HeaderHXRedirect = "HX-Redirect" HeaderHXRefresh = "HX-Refresh" HeaderHXReplaceURL = "HX-Replace-Url" HeaderHXReswap = "HX-Reswap" HeaderHXRetarget = "HX-Retarget" HeaderHXReselect = "HX-Reselect" HeaderHXTrigger = "HX-Trigger" HeaderHXTriggerAfterSwap = "HX-Trigger-After-Swap" HeaderHXTriggerAfterSettle = "HX-Trigger-After-Settle" )
const ( HeaderHXRequest = "HX-Request" HeaderHXBoosted = "HX-Boosted" HeaderHXCurrentURL = "HX-Current-URL" HeaderHXHistoryRestoreRequest = "HX-History-Restore-Request" HeaderHXPrompt = "HX-Prompt" HeaderHXTarget = "HX-Target" HeaderHXTriggerName = "HX-Trigger-Name" )
Variables ¶
This section is empty.
Functions ¶
func Location ¶
func Location(w http.ResponseWriter, r *http.Request, path string)
Location performs a client-side navigation with URL update and history entry.
func LocationTarget ¶
func LocationTarget(w http.ResponseWriter, r *http.Request, path, target string)
LocationTarget performs a client-side navigation that updates a specific element.
func LocationWithOptions ¶
func LocationWithOptions(w http.ResponseWriter, r *http.Request, opts LocationOptions)
LocationWithOptions performs a client-side navigation with full HTMX location options.
func Redirect ¶
func Redirect(w http.ResponseWriter, r *http.Request, url string)
Redirect performs a redirect for both HTMX and regular requests.
func RedirectBack ¶
func RedirectBack(w http.ResponseWriter, r *http.Request, fallback string)
RedirectBack redirects to the URL in the "redirect" query parameter, or fallback if not present.
func RedirectWithStatus ¶
RedirectWithStatus performs a redirect with a custom status code.
Types ¶
type Config ¶
type Config struct {
OOBComponents []Renderable
Retarget string
Reswap SwapStrategy
Reselect string
PushURL string
ReplaceURL string
Triggers []string
TriggersAfterSwap []string
TriggersAfterSettle []string
Refresh bool
}
Config holds HTMX render configuration. Exported so internal/context.go can access OOB components.
func NewConfig ¶
func NewConfig(opts ...RenderOption) *Config
NewConfig creates a Config from options.
func (*Config) ApplyHeaders ¶
func (c *Config) ApplyHeaders(w http.ResponseWriter)
ApplyHeaders sets HTMX headers on the response. Called by Context.Render() before WriteHeader.
type LocationOptions ¶
type LocationOptions struct {
Path string `json:"path"`
Source string `json:"source,omitempty"`
Event string `json:"event,omitempty"`
Handler string `json:"handler,omitempty"`
Target string `json:"target,omitempty"`
Swap string `json:"swap,omitempty"`
Values map[string]string `json:"values,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Select string `json:"select,omitempty"`
}
LocationOptions represents the configuration for HX-Location header.
type RenderOption ¶
type RenderOption func(*Config)
RenderOption configures HTMX render behavior.
func WithOOB ¶
func WithOOB(components ...Renderable) RenderOption
WithOOB appends out-of-band components to render after the main component. Components must include id and hx-swap-oob attributes.
func WithPushURL ¶
func WithPushURL(url string) RenderOption
WithPushURL sets the HX-Push-Url header to update browser history. Pass "false" to prevent URL update.
func WithRefresh ¶
func WithRefresh() RenderOption
WithRefresh sets the HX-Refresh header to force a full page refresh.
func WithReplaceURL ¶
func WithReplaceURL(url string) RenderOption
WithReplaceURL sets the HX-Replace-Url header to replace current URL. Pass "false" to prevent URL replacement.
func WithReselect ¶
func WithReselect(selector string) RenderOption
WithReselect sets the HX-Reselect header to select a subset of the response.
func WithReswap ¶
func WithReswap(strategy SwapStrategy) RenderOption
WithReswap sets the HX-Reswap header to change the swap strategy.
func WithRetarget ¶
func WithRetarget(selector string) RenderOption
WithRetarget sets the HX-Retarget header to change the target element.
func WithTrigger ¶
func WithTrigger(events ...string) RenderOption
WithTrigger sets the HX-Trigger header to trigger client-side events. Multiple events are comma-joined.
func WithTriggerAfterSettle ¶
func WithTriggerAfterSettle(events ...string) RenderOption
WithTriggerAfterSettle sets the HX-Trigger-After-Settle header. Events trigger after the settle phase.
func WithTriggerAfterSwap ¶
func WithTriggerAfterSwap(events ...string) RenderOption
WithTriggerAfterSwap sets the HX-Trigger-After-Swap header. Events trigger after the swap completes.
type Renderable ¶
Renderable is the interface for OOB components. Compatible with templ.Component and forge.Component.
type SwapStrategy ¶
type SwapStrategy string
SwapStrategy defines how HTMX should swap content into the target element.
const ( SwapInnerHTML SwapStrategy = "innerHTML" // Replace the inner html of the target element SwapOuterHTML SwapStrategy = "outerHTML" // Replace the entire target element with the response SwapBeforeBegin SwapStrategy = "beforebegin" // Insert before the target element SwapAfterBegin SwapStrategy = "afterbegin" // Insert before the first child of the target element SwapBeforeEnd SwapStrategy = "beforeend" // Insert after the last child of the target element SwapAfterEnd SwapStrategy = "afterend" // Insert after the target element SwapDelete SwapStrategy = "delete" // Delete the target element SwapNone SwapStrategy = "none" // Do not swap content )