Help us shape the future of Go! Take the 2026 Go Developer Survey

htmx

package
v0.0.0-...-b1aaf46 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 14, 2026 License: AGPL-3.0 Imports: 8 Imported by: 4

Documentation

Index

Constants

View Source
const (
	// Request header that is "true" if the request was made from an element using 'hx-boost'.
	HeaderBoosted = "HX-Boosted"
	// Request header for the current URL of the browser.
	HeaderCurrentURL = "HX-Current-URL"
	// Request header that is “true” if the request is for history restoration after a miss in the local history cache.
	HeaderHistoryRestoreRequest = "HX-History-Restore-Request"
	// Request header that is always “true” for HTMX requests.
	HeaderRequest = "Hx-Request"
	// Request header of the id of the target element if it exists.
	HeaderTarget = "HX-Target"
	// HeaderRequestType indicates which type of HTMX request this is, "full" or "partial".
	HeaderRequestType = "HX-Request-Type"
	// HeaderSource request header contains the element that triggered the request. Format is tag#id like button#submit.
	HeaderSource = "HX-Source"
)

HTTP request headers

View Source
const (
	// Response header that allows you to do a client-side redirect that does not do a full page reload.
	HeaderLocation = "HX-Location"
	// Response header that pushes a new url into the history stack.
	HeaderPushURL = "HX-Push-Url"
	// Response header that can be used to do a client-side redirect to a new location.
	HeaderRedirect = "HX-Redirect"
	// Response header that if set to “true” the client-side will do a full refresh of the page.
	HeaderRefresh = "HX-Refresh"
	// Response header that replaces the current URL in the location bar.
	HeaderReplaceUrl = "HX-Replace-Url"
	// Response header that allows you to specify how the response will be swapped.
	HeaderReswap = "HX-Reswap"
	// Response header that uses a CSS selector that updates the target of the content update to a
	// different element on the page.
	HeaderRetarget = "HX-Retarget"
	// Response header that uses a CSS selector that allows you to choose which
	// part of the response is used to be swapped in. Overrides an existing hx-select
	// on the triggering element.
	HeaderReselect = "HX-Reselect"
	// Response header that allows you to trigger client-side events after the settle step.
	HeaderTriggerAfterSettle = "HX-Trigger-After-Settle"
	// Response header that allows you to trigger client-side events after the swap step.
	HeaderTriggerAfterSwap = "HX-Trigger-After-Swap"
	// HeaderTrigger response header triggers client-side events after the swap has completed.
	HeaderTrigger = "HX-Trigger"
)

HTTP response headers

View Source
const StatusStopPolling int = 286

286 Stop Polling

HTTP status code that tells HTMX to stop polling from a server response.

For more info, see https://htmx.org/docs/#load_polling

Variables

RequestHeaders contains all valid HTMX request headers.

https://htmx.org/reference/#request_headers

ResponseHeaders contains all valid HTMX response headers.

https://htmx.org/reference/#response_headers

Functions

func GetCurrentURL

func GetCurrentURL(r *http.Request) (string, bool)

GetCurrentURL returns the current URL that HTMX made this request from.

Returns false if header 'HX-Current-URL' does not exist.

func GetTarget

func GetTarget(r *http.Request) (string, bool)

GetTarget returns the ID of the target element if it exists from a given request.

Returns false if header 'HX-Target' does not exist.

For more info, see https://htmx.org/attributes/hx-target/

func IsBoosted

func IsBoosted(r *http.Request) bool

IsBoosted returns true if the given request was made via an element using 'hx-boost'.

This can be used to add special logic for boosted requests.

Checks if header 'HX-Boosted' is 'true'.

For more info, see https://htmx.org/attributes/hx-boost/

func IsHTMX

func IsHTMX(r *http.Request) bool

IsHTMX returns true if the given request was made by HTMX.

This can be used to add special logic for HTMX requests.

Checks if header 'HX-Request' is 'true'.

func IsHistoryRestoreRequest

func IsHistoryRestoreRequest(r *http.Request) bool

IsHistoryRestoreRequest returns true if the given request is for history restoration after a miss in the local history cache.

Checks if header 'HX-History-Restore-Request' is 'true'.

func LocationResponse

func LocationResponse(options ...LocationOption) http.HandlerFunc

LocationResponse creates and sets the HX-Location header on the response as per the given options.

func RequireHTMX

func RequireHTMX(next http.Handler) http.Handler

RequireHTMX middleware will only pass control to the next handler if the request is HTMX powered. If not, it will return 403: Forbidden response.

func SetupHTMX

func SetupHTMX(next http.Handler) http.Handler

SetupHTMX middleware performs general setup for serving HTMX-powered content.

Types

type Attributes

type Attributes struct {
	// contains filtered or unexported fields
}

Attributes represents htmx hx-* attributes applied to an element.

func NewAttributes

func NewAttributes(options ...AttributesOption) *Attributes

NewAttributes creates a Attributes object for an element with the given options.

func (*Attributes) GetAttributes

func (p *Attributes) GetAttributes() templ.Attributes

GetAttributes returns the hx-* attributes as a templ.Attributes.

func (*Attributes) HasAttribute

func (p *Attributes) HasAttribute(key string) bool

HasAttribute returns a boolean indicating whether there is an attribute with the given key.

func (*Attributes) SetAttribute

func (p *Attributes) SetAttribute(key string, value any)

SetAttribute sets an attribute with the given key to the given value. Any existing value is overridden.

type AttributesOption

type AttributesOption func(*Attributes)

AttributesOption is a functional option to set Properties.

func WithHXInclude

func WithHXInclude(value string) AttributesOption

WithHXInclude sets the hx-include attribute.

func WithHXMethod

func WithHXMethod(method, value string) AttributesOption

WithHXMethod sets the method attribute (i.e., hx-get, hx-post, etc.) to the given value.

func WithHXPushURL

func WithHXPushURL(value any) AttributesOption

WithHXPushURL sets hx-push-url to true.

func WithHXReplaceURL

func WithHXReplaceURL(value any) AttributesOption

WithHXReplaceURL sets hx-replace-url to true.

func WithHXSwap

func WithHXSwap(value string) AttributesOption

WithHXSwap sets the hx-swap attribute.

func WithHXTarget

func WithHXTarget(target string) AttributesOption

WithHXTarget sets the hx-target attribute.

func WithHXTrigger

func WithHXTrigger(value string) AttributesOption

WithHXTrigger sets the hx-trigger attribute.

func WithHXVals

func WithHXVals(vals any) AttributesOption

WithHXVals sets the hx-vals attribute. It can handle a string value directly or a map of values which will get marshaled into a JSON string representation.

type Config

type Config struct {
	// Logall defaults to false, if set to true htmx will log all events to the console for debugging.
	LogAll *bool `json:"logAll,omitempty"`
	// Prefix defaults to "data-hx-", a secondary attribute prefix recognised alongside the always-active hx- prefix
	// (e.g. data-hx-get works by default). Set to "" to disable. Must be set via meta tag, setting this after page load
	// will not apply correctly.
	Prefix string `json:"prefix,omitzero"`
	// Transitions defaults to false, whether to use view transitions when swapping content (if browser supports it).
	Transitions *bool `json:"transitions,omitempty"`
	// History defaults to true, whether to enable history support. Set to "reload" to do a full page reload on history
	// navigation instead of an AJAX request.
	History *bool `json:"history,omitempty"`
	// Mode defaults to 'same-origin', the fetch mode for AJAX requests. Can be 'cors', 'no-cors', or 'same-origin'.
	Mode Mode `json:"mode,omitzero" validate:"omitempty,oneof=cors no-cors same-origin"`
	// DefaultSwap defaults to "innerMorph".
	DefaultSwap string `json:"defaultSwap,omitzero"`
	// IndicatorClass defaults to "htmx-indicator".
	IndicatorClass string `json:"indicatorClass,omitzero"`
	// RequestClass defaults to "htmx-request".
	RequestClass string `json:"requestClass,omitzero"`
	// IncludeIndicatorCSS defaults to true (determines if the indicator styles are loaded).
	IncludeIndicatorCSS *bool `json:"includeIndicatorCSS,omitempty"`
	// DefaultTimeout defaults to 60000 (60 seconds), the number of milliseconds a request can take before automatically
	// being terminated.
	DefaultTimeout int `json:"defaultTimeout" validate:"omitempty,gt=0"`
	// InlineScriptNonce defaults to unset, meaning that no nonce will be added to inline scripts.
	InlineScriptNonce string `json:"inlineScriptNonce,omitzero"`
	// Extensions defaults to ”, a comma-separated list of extension names to load (e.g., 'preload,pending').
	Extensions string `json:"extensions,omitzero"`
	// MorphIgnore defaults to ["data-htmx-powered"], array of attribute name prefixes to preserve when morphing
	// elements.
	MorphIgnore string `json:"morphIgnore,omitzero"`
	// MorphScanLimit limits the number of nodes scanned during morphing.
	MorphScanLimit int `json:"morphScanLimit,omitzero" validate:"omitempty,gt=0"`
	// MorphSkip defaults to '[hx-morph-skip]', CSS selector for elements to completely skip during morphing (they stay
	// frozen).
	MorphSkip string `json:"morphSkip,omitzero"`
	// MorphSkipChildren defaults to '[hx-morph-skip-children]', CSS selector for elements whose attributes update but
	// children are preserved during morphing.
	MorphSkipChildren string `json:"morphSkipChildren,omitzero"`
	// NoSwap defaults to [204, 304], array of HTTP status codes that should not trigger a swap.
	NoSwap []int `json:"noSwap,omitzero"`
	// AllowEmptySwapAfterOOB defaults to false, whether the main swap still runs when a response contained only
	// out-of-band elements.
	AllowEmptySwapAfterOOB *bool `json:"allowEmptySwapAfterOOB,omitempty"`
	// ImplicitInheritance defaults to false, if set to true attributes will be inherited from parent elements
	// automatically without requiring the :inherited modifier.
	ImplicitInheritance *bool `json:"implicitInheritance,omitempty"`
	// DefaultFocusScroll defaults to false, whether to scroll focused elements into view after swap.
	DefaultFocusScroll *bool `json:"defaultFocusScroll,omitempty"`
	// DefaultSettleDelay defaults to 1 (ms), delay between swap and settle phases.
	DefaultSettleDelay int `json:"defaultSettleDelay,omitzero" validate:"omitempty,gt=0"`
	// MetaCharacter defaults to undefined, allows you to use a custom character instead of : for attribute modifiers
	// (e.g., - to use hx-get-inherited instead of hx-get:inherited).
	MetaCharacter string `json:"metaCharacter,omitzero"`
}

Config defines the htmx config options.

https://htmx.org/docs/#config

type HXLocationRequest

type HXLocationRequest struct {
	// The URL path.
	Path string `json:"path"`
	//  The source element of the request.
	Source string `json:"source,omitzero"`
	// An event that “triggered” the request.
	Event string `json:"event,omitzero"`
	// A JS callback that will handle the response HTML.
	Handler string `json:"handler,omitzero"`
	// The target to swap the response into.
	Target string `json:"target,omitzero"`
	// How the response will be swapped in relative to the target.
	Swap string `json:"swap,omitzero"`
	// Values to submit with the request.
	Values any `json:"values,omitzero"`
	// Headers to submit with the request.
	Headers map[string]string `json:"headers,omitzero"`
	// Allows you to select the content you want swapped from a response.
	Select string `json:"select,omitzero"`
	// Set to 'false' or a path string to prevent or override the URL pushed to browser location history
	Push string `json:"push,omitzero"`
	// A path string to replace the URL in the browser location history
	Replace string `json:"replace,omitzero"`
}

HXLocationRequest defines the value of the HX-Location header.

https://htmx.org/headers/hx-location/

type ID

type ID string

ID represents an id attribute in a HTML element.

func (ID) String

func (a ID) String() string

String returns the id attribute as a string.

func (ID) Target

func (a ID) Target() string

Target returns the id attribute as a target (i.e., for htmx requests). This is the base id string with a "#" prefix.

type LocationOption

type LocationOption func(*HXLocationRequest)

LocationOption is a functional option applied to a HX-Location request.

func WithLocationEvent

func WithLocationEvent(source string) LocationOption

WithLocationEvent option sets an event that “triggered” the request.

func WithLocationHandler

func WithLocationHandler(handler string) LocationOption

WithLocationHandler option sets a callback that will handle the response HTML.

func WithLocationHeaders

func WithLocationHeaders(headers map[string]string) LocationOption

WithLocationHeaders option sets headers to submit with the request.

func WithLocationPath

func WithLocationPath(path string) LocationOption

WithLocationPath option sets the path to which the request will be sent.

func WithLocationPush

func WithLocationPush(push string) LocationOption

WithLocationPush option if set to 'false' or a path string to prevent or override the URL pushed to browser location history.

func WithLocationReplace

func WithLocationReplace(replace string) LocationOption

WithLocationReplace option sets a path string to replace the URL in the browser location history.

func WithLocationSelect

func WithLocationSelect(sel string) LocationOption

WithLocationSelect option allows you to select the content you want swapped from a response.

func WithLocationSource

func WithLocationSource(source string) LocationOption

WithLocationSource option sets the source element of the request.

func WithLocationSwap

func WithLocationSwap(swap string) LocationOption

WithLocationSwap option sets how the response will be swapped in relative to the target.

func WithLocationTarget

func WithLocationTarget(target string) LocationOption

WithLocationTarget option sets the target to swap the response into.

func WithLocationValues

func WithLocationValues(values any) LocationOption

WithLocationValues option sets values to submit with the request.

type Mode

type Mode string
const (
	ModeCORS       Mode = "cors"
	ModeNoCORS     Mode = "no-cors"
	ModeSameOrigin Mode = "same-origin"
)

type ResponseHandling

type ResponseHandling struct {
	// Code is a String representing a regular expression that will be tested against response codes.
	Code string `json:"code"`
	// Swap is true if the response should be swapped into the DOM, false otherwise.
	Swap bool `json:"swap"`
	// Error is true if htmx should treat this response as an error.
	Error bool `json:"error,omitempty,omitzero"`
	// IgnoreTitle is true if htmx should ignore title tags in the response.
	IgnoreTitle bool `json:"ignoreTitle,omitempty,omitzero"`
	// Select is a CSS selector to use to select content from the response.
	Select string `json:"select,omitempty,omitzero"`
	// Target is a CSS selector specifying an alternative target for the response.
	Target string `json:"target,omitempty,omitzero"`
	// SwapOverride is an alternative swap mechanism for the response.
	SwapOverride string `json:"swapOverride,omitempty,omitzero"`
}

ResponseHandling configures how htmx handles different HTTP response codes. When htmx receives a response it will iterate in order over the htmx.config.responseHandling array and test if the code property of a given object, when treated as a Regular Expression, matches the current response. If an entry does match the current response code, it will be used to determine if and how the response will be processed.

https://htmx.org/docs/#response-handling

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL