hx

package module
v4.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2026 License: MIT Imports: 6 Imported by: 0

README

HTMX library for Go

Go Reference

hxgo provides request-header helpers and response-header builders for HTMX v4. It works with Go's standard net/http package and includes helpers for Echo, Fiber, and Gin.

Version support

This module, github.com/stackus/hxgo/v4, supports HTMX v4. Version 1 remains available for HTMX v2 users at github.com/stackus/hxgo, without the /v4 module suffix.

Installation

The module requires Go 1.27.1 or later.

go get github.com/stackus/hxgo/v4
import "github.com/stackus/hxgo/v4"

Overview

Use request helpers to inspect HTMX request headers and Headers to add HTMX response headers to a standard http.ResponseWriter.

package main

import (
	"net/http"

	"github.com/stackus/hxgo/v4"
)

func handler(w http.ResponseWriter, r *http.Request) {
	if !hx.IsHtmx(r) {
		return
	}

	err := hx.Headers(w,
		hx.Location("/account").
			Target("#content").
			Swap(hx.SwapInnerHtml.IgnoreTitle()),
		hx.Trigger(
			"account-updated",
			hx.Event("toast", map[string]string{"message": "Saved"}),
		),
	)
	if err != nil {
		http.Error(w, "unable to build HTMX response", http.StatusInternalServerError)
		return
	}

	_, _ = w.Write([]byte("<p>Account updated.</p>"))
}

Working with requests

The request helpers read HTMX request headers from *http.Request. Each adapter package exposes the same helpers for its framework context.

Request header Constant Helper
HX-Boosted HxBoosted IsBoosted
HX-Current-URL HxCurrentUrl GetCurrentUrl
HX-History-Restore-Request HxHistoryRestoreRequest IsHistoryRestoreRequest
HX-Request HxRequest IsRequest, IsHtmx
HX-Request-Type HxRequestType GetRequestType, IsRequestTypeFull, IsRequestTypePartial
HX-Source HxSource GetSource
HX-Target HxTarget GetTarget

Is* helpers report whether the relevant header is present, except IsRequestTypeFull and IsRequestTypePartial, which compare HX-Request-Type with full and partial. Get* helpers return an empty string when their header is absent.

func handler(w http.ResponseWriter, r *http.Request) {
	if hx.IsRequestTypePartial(r) {
		// Render a partial response.
		return
	}
	if hx.IsRequestTypeFull(r) {
		// Render a full-page response.
	}
}

Working with responses

Headers applies HeaderOption values to an http.ResponseWriter. It only sets response headers; write the status code and response body with the usual facilities of your HTTP framework after calling it.

func handler(w http.ResponseWriter, r *http.Request) {
	if err := hx.Headers(w,
		hx.Retarget("#messages"),
		hx.Reselect("#message-list"),
		hx.PushUrl("/messages"),
	); err != nil {
		http.Error(w, "unable to build HTMX response", http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte("<ul id=\"message-list\"></ul>"))
}

HeaderOption is the common option interface. HeaderOptionFunc is the function form used by options such as Trigger, Refresh, ReplaceUrl, and PushUrl.

Building headers for another HTTP package

BuildHeaders returns an *HxHeaders without writing a response. Use HxHeaders.Headers() to obtain the constructed header map when integrating with a package that does not use http.ResponseWriter.

headers, err := hx.BuildHeaders(
	hx.Redirect("/sign-in"),
	hx.Trigger("session-expired"),
)
if err != nil {
	return err
}

for name, value := range headers.Headers() {
	// Set name and value with the target framework's response API.
	_ = name
	_ = value
}
Response headers and options
Response header Constant Option
HX-Location HxLocation Location
HX-Redirect HxRedirect Redirect
HX-Refresh HxRefresh Refresh
HX-Retarget HxRetarget Retarget
HX-Reswap HxReswap Reswap or a Swap* constant
HX-Reselect HxReselect Reselect
HX-Replace-Url HxReplaceUrl ReplaceUrl
HX-Push-Url HxPushUrl PushUrl
HX-Trigger HxTrigger Trigger

Redirect, Retarget, Reswap, and Reselect are string types that can be passed directly to Headers. Refresh() sets HX-Refresh: true. ReplaceUrl and PushUrl accept either a string URL or false to disable the corresponding history behavior.

err := hx.Headers(w,
	hx.Redirect("/sign-in"),
	hx.Refresh(),
	hx.ReplaceUrl(false),
	hx.PushUrl("/projects"),
)
Location

Calling Location(path) sets HX-Location. With only a path, it writes that path directly. Calling a fluent method makes the header a JSON object containing the path and configured properties.

Method Location property
Source(string) source
Event(string) event
Target(string) target
Swap(string | Reswap | *ReswapModifiers) swap
Transition() transition: "true"
Values(any) values
Headers(map[string]string) headers
Select(string) select
SelectOOB(string) selectOOB
err := hx.Headers(w,
	hx.Location("/search").
		Source("button#search").
		Event("click").
		Target("#results").
		Swap(hx.SwapInnerMorph.Transition()).
		Select("#results").
		SelectOOB("#notifications").
		Values(map[string]string{"query": "go"}).
		Headers(map[string]string{"X-Requested-With": "search"}),
)
Reswap

Reswap overrides the swap strategy selected by the triggering element. Pass a custom Reswap string or one of these constants:

Constant Swap strategy
SwapInnerHtml Replace an element's content.
SwapOuterHtml Replace an entire element.
SwapTextContent Replace text without parsing HTML.
SwapBefore Insert before an element.
SwapPrepend Insert as the first child.
SwapAppend Insert as the last child.
SwapAfter Insert after an element.
SwapInnerMorph Morph an element's content.
SwapOuterMorph Morph an entire element.
SwapOuterSync Morph target attributes, then replace children.
SwapDelete Remove the target.
SwapNone Do not insert response content.
SwapUpsert Update elements by ID and insert new elements.

Modifiers are fluent and can be chained:

Modifier Behavior
Transition() Enable view transitions.
Swap(string | time.Duration) Set the swap delay.
Settle(string | time.Duration) Set the settle delay.
IgnoreTitle() Keep the current document title.
ScrollTop() / ScrollBottom() Scroll to the target edge; pass true for the window or a selector for another target.
ShowTop() / ShowBottom() Show the target edge; optionally pass another selector.
ShowNone() Disable automatic show scrolling.
FocusScroll(bool) Control scrolling when restored focus is brought into view.
Target(string) Set the swap target.
Strip(bool) Control removal of the response's outer element.
SwapEmpty(bool) Control swaps for an empty response.
err := hx.Headers(w,
	hx.SwapOuterMorph.
		Transition().
		Swap("200ms").
		Settle("100ms").
		IgnoreTitle().
		ScrollTop("#results").
		ShowNone().
		FocusScroll(true).
		Target("#content").
		Strip(false).
		SwapEmpty(true),
)
Trigger events

Trigger sets HX-Trigger. It accepts simple event names as strings, TriggerEvent values returned by Event, or both. A simple event is emitted as a comma-separated name. Event(name) creates a named event; one data value is encoded directly, while two or more are encoded as an array.

err := hx.Headers(w,
	hx.Trigger(
		"refresh-sidebar",
		hx.Event("toast", map[string]string{"message": "Saved"}),
		hx.Event("selected", "first", "second"),
	),
)

Framework adapters

The hxecho, hxfiber, and hxgin packages provide the same request-header constants/helpers and a Headers function for their framework context. They re-export response constants, option types, and convenience functions needed to build headers with the adapter package.

Framework Import path Response helper
Echo v5 github.com/stackus/hxgo/v4/hxecho hxecho.Headers(*echo.Context, ...)
Fiber v3 github.com/stackus/hxgo/v4/hxfiber hxfiber.Headers(fiber.Ctx, ...)
Gin github.com/stackus/hxgo/v4/hxgin hxgin.Headers(*gin.Context, ...)

For example, with Echo v5:

package main

import (
	"net/http"

	"github.com/labstack/echo/v5"
	"github.com/stackus/hxgo/v4/hxecho"
)

func main() {
	e := echo.New()
	e.GET("/", func(c *echo.Context) error {
		if hxecho.IsHtmx(c) {
			if err := hxecho.Headers(c,
				hxecho.Location("/account").Target("#content"),
				hxecho.Trigger("account-loaded"),
			); err != nil {
				return err
			}
		}
		return c.String(http.StatusOK, "Hello Echo")
	})
	e.Logger.Fatal(e.Start(":8080"))
}

Contributing

Contributions are welcome. Please open an issue or submit a pull request. Bug reports should include a clear description, reproduction steps, and useful logs or screenshots. Please check for existing issues before creating a new one.

License

This project is licensed under the MIT License. See LICENSE.

Documentation

Index

Constants

View Source
const (
	// HxBoosted is set to "true" when the request comes from a boosted element via hx-boost.
	//
	// Contents: "true" or not set
	//
	// See https://four.htmx.org/reference/headers/HX-Boosted for more details.
	//
	// Use the IsBoosted() function to check this header in the request.
	HxBoosted = "Hx-Boosted"

	// HxCurrentUrl contains the browser’s URL when the request was made.
	//
	// Contents: URL
	//
	// See https://four.htmx.org/reference/headers/HX-Current-URL for more details.
	//
	// Use the GetCurrentUrl() function to fetch this header from the request.
	HxCurrentUrl = "Hx-Current-URL"

	// HxHistoryRestoreRequest is set to "true" when the user navigates back or forward in history.
	//
	// Contents: "true" or not set
	//
	// See https://four.htmx.org/reference/headers/HX-History-Restore-Request for more details.
	//
	// Use the IsHistoryRestoreRequest() function to check this header in the request.
	HxHistoryRestoreRequest = "Hx-History-Restore-Request"

	// HxRequest indicates the request was made by htmx.
	//
	// Contents: "true"
	//
	// See https://four.htmx.org/reference/headers/HX-Request for more details.
	//
	// Use the IsRequest() function to check this header in the request.
	HxRequest = "Hx-Request"

	// HxRequestType indicates if request targets a specific element or the whole page.
	//
	// Contents: "partial" or "full"
	//
	// See https://four.htmx.org/reference/headers/HX-Request-Type for more details.
	//
	// Use the GetRequestType() function to fetch this header from the request.
	HxRequestType = "Hx-Request-Type"

	// HxSource contains the element that triggered the request. Format is tag#id like button#submit.
	//
	// Contents: Element reference
	//
	// See https://four.htmx.org/reference/headers/HX-Source for more details.
	//
	// Use the GetSource() function to fetch this header from the request.
	HxSource = "Hx-Source"

	// HxTarget identifies the element that will receive the response.
	//
	// Contents: Element reference
	//
	// See https://four.htmx.org/reference/headers/HX-Target for more details.
	//
	// Use the GetTarget() function to fetch this header from the request.
	HxTarget = "Hx-Target"
)

Request Headers

View Source
const (
	// HxTrigger triggers client-side events after the swap has completed.
	//
	// See https://four.htmx.org/reference/headers/HX-Trigger for more details.
	//
	// Use the Trigger(...TriggerEvent) option to set this header in the response.
	HxTrigger = "Hx-Trigger"

	// HxLocation redirects without reloading the page.
	//
	// See https://four.htmx.org/reference/headers/HX-Location for more details.
	//
	// Use the Location(string) option to set this header in the response.
	HxLocation = "Hx-Location"

	// HxRedirect redirects to a new URL with a full page reload.
	//
	// Use it for non-htmx endpoints or pages that require a full browser load.
	//
	// For AJAX navigation inside an htmx application, send HxLocation with Location(path).
	//
	// See https://four.htmx.org/reference/headers/HX-Redirect for more details.
	//
	// Use the Redirect(string) option to set this header in the response.
	HxRedirect = "Hx-Redirect"

	// HxRefresh when set to true, reloads the entire page.
	//
	// See https://four.htmx.org/reference/headers/HX-Refresh for more details.
	//
	// Use the Refresh() option to set this header in the response.
	HxRefresh = "Hx-Refresh"

	// HxRetarget overrides the element that'll receive the swapped content, replacing whatever hx-target was set on the triggering element.
	//
	// See https://four.htmx.org/reference/headers/HX-Retarget for more details.
	//
	// Use the Retarget(string) option to set this header in the response.
	HxRetarget = "Hx-Retarget"

	// HxReswap overrides the swap style used when inserting the response, replacing whatever hx-swap was set on the triggering element.
	//
	// See https://four.htmx.org/reference/headers/HX-Reswap for more details.
	//
	// Use either:
	//	- SwapInnerHtml   : Replaces content inside element.
	//	- SwapOuterHtml   : Replaces entire element.
	//	- SwapTextContent : Replaces the text content of the element, without parsing the response as HTML.
	//	- SwapBefore      : Inserts content before element.
	//	- SwapPrepend     : Inserts content as first child.
	//	- SwapAppend      : Inserts content as last child.
	//	- SwapAfter       : Inserts content after element.
	//	- SwapInnerMorph  : Morphs content inside element, preserving state and focus.
	//	- SwapOuterMorph  : Morphs entire element, preserving state and focus.
	//	- SwapOuterSync   : Morphs the target’s attributes, then replaces its children.
	//	- SwapDelete      : Removes element (ignores response content).
	//	- SwapNone        : Doesn’t insert content.
	//	- SwapUpsert      : Updates existing elements by ID and inserts new ones.
	//  - Reswap(string)  : Set a custom swap style.
	HxReswap = "Hx-Reswap"

	// HxReselect allows selection of a specific part of the response to be swapped in, using a CSS selector. It overrides any existing hx-select on the triggering element.
	//
	// See https://four.htmx.org/reference/headers/HX-Reselect for more details.
	//
	// Use the Reselect(string) option to set this header.
	HxReselect = "Hx-Reselect"

	// HxReplaceUrl replaces the current browser history URL.
	//
	// See https://four.htmx.org/reference/headers/HX-Replace-Url for more details.
	//
	// Use the ReplaceUrl(string) option to set this header in the response.
	HxReplaceUrl = "Hx-Replace-Url"

	// HxPushUrl pushes a new URL into the history stack.
	//
	// See https://htmx.org/reference/#response_headers for more details.
	//
	// Use the PushUrl(string) option to set this header in the response.
	HxPushUrl = "Hx-Push-Url"
)

Headers Headers

Variables

This section is empty.

Functions

func GetCurrentUrl

func GetCurrentUrl(r *http.Request) string

GetCurrentUrl extracts the HxCurrentUrl header from an HTTP request.

Returns the current URL of the browser if the header exists.

func GetRequestType

func GetRequestType(r *http.Request) string

GetRequestType extracts the HxRequestType header from an HTTP request.

Returns either "partial" or "full"

func GetSource

func GetSource(r *http.Request) string

GetSource extracts the HxSource header from an HTTP request.

Returns the element reference of the source if the header exists.

func GetTarget

func GetTarget(r *http.Request) string

GetTarget extracts the HxTarget header from an HTTP request.

Returns the element reference of the target if the header exists.

func Headers

func Headers(w http.ResponseWriter, options ...HeaderOption) error

Headers modify the http.ResponseWriter to add HTMX headers.

The following options are available:

  • Status(int) | StatusStopPolling: Sets the HTTP status code of the HTMX response.
  • Location(path): Enables client-side redirection without a full page reload.
  • PushUrl(string): Pushes a new URL into the history stack.
  • Redirect(string): Performs a client-side redirect with a full page reload.
  • Refresh(bool): If set to "true", triggers a full refresh of the client-side page.
  • ReplaceUrl(string): Replaces the current URL in the location bar.
  • Reswap(string) | {Swap constants}: Specifies an override for how the response will be swapped.
  • Retarget(string): A CSS selector to update the target of the content update to a different page element.
  • Reselect(string): A CSS selector to select a part of the response to be swapped in, overriding existing hx-select on the triggering element.
  • Trigger(...TriggerEvent): Triggers client-side events.

func IsBoosted

func IsBoosted(r *http.Request) bool

IsBoosted checks the HxBoosted header

Returns true if the request is a boosted request

func IsHistoryRestoreRequest

func IsHistoryRestoreRequest(r *http.Request) bool

IsHistoryRestoreRequest checks the HxHistoryRestoreRequest header

Returns true if the header is present, otherwise returns false.

func IsHtmx

func IsHtmx(r *http.Request) bool

IsHtmx determines if an HTTP request is an HTMX request.

Does the same thing as IsRequest, only with a more user-friendly name.

func IsRequest

func IsRequest(r *http.Request) bool

IsRequest determines if an HTTP request is an HTMX request by checking the HxRequest header

Returns true if the header is present, otherwise returns false.

func IsRequestTypeFull

func IsRequestTypeFull(r *http.Request) bool

IsRequestTypeFull determines if the HxRequestType was "full"

Returns true if the HxRequestType was "full", otherwise returns false.

func IsRequestTypePartial

func IsRequestTypePartial(r *http.Request) bool

IsRequestTypePartial determines if the HxRequestType was "partial"

Returns true if the HxRequestType was "partial", otherwise returns false.

Types

type HeaderOption

type HeaderOption interface {
	// contains filtered or unexported methods
}

HeaderOption is the interface that can be used to set the headers and status code of the response

type HeaderOptionFunc

type HeaderOptionFunc func(*HxHeaders)

HeaderOptionFunc is a function that can be used to set the headers and status code of the response

func PushUrl

func PushUrl(url any) HeaderOptionFunc

PushUrl replaces the current browser history URL. It creates a new entry for back and forward navigation.

More details: https://four.htmx.org/reference/headers/HX-Push-Url

Example usage:

hx.Headers(w, hx.PushUrl("/relative-path"))
// Sets the HX-Push-Url header to "/relative-path".
hx.Headers(w, hx.PushUrl(false))
// Sets the HX-Push-Url header to "false".

func Refresh

func Refresh() HeaderOptionFunc

Refresh sets the HxRefresh header.

More details: https://four.htmx.org/reference/headers/HX-Refresh

When set, it triggers a full refresh of the client-side page.

Example usage:

hx.Headers(w, hx.Refresh())
// Sets the HX-Refresh header to "true".

func ReplaceUrl

func ReplaceUrl(url any) HeaderOptionFunc

ReplaceUrl replaces the current browser history URL. It does not create a new history entry.

More details: https://four.htmx.org/reference/headers/HX-Replace-Url

Example usage:

hx.Headers(w, hx.ReplaceUrl("/relative-path"))
// Sets the HX-Replace-Url header to "/relative-path".
hx.Headers(w, hx.ReplaceUrl(false))
// Sets the HX-Replace-Url header to "false".

func Trigger

func Trigger(events ...any) HeaderOptionFunc

Trigger allows you to trigger events on the client

More details: https://four.htmx.org/reference/headers/HX-Trigger

Use Event to create events to pass to this option.

Send simple events:

hx.Headers(w, hx.Trigger("myEvent"))
// Sets HX-Trigger header to "myEvent"

Send multiple simple events:

hx.Headers(w, hx.Trigger("myEvent", "myOtherEvent"))
// Sets HX-Trigger header to `myEvent, myOtherEvent`

Send complex events with data:

hx.Headers(w, hx.Trigger(hx.Event("myEvent", "myData")))
// Sets HX-Trigger header to `{"myEvent":"myData"}`

Send multiple complex events with data:

hx.Headers(w, hx.Trigger(
    hx.Event("myEvent", "myData"),
    hx.Event("myOtherEvent", map[string]any{"fieldA": "keyA"}),
))
// Sets HX-Trigger header to `{"myEvent":"myData","myOtherEvent":{"fieldA":"keyA"}}`

Send simple and complex events together

hx.Headers(w, hx.Trigger(
    "simpleOne", "simpleTwo",
    hx.Event("myEvent", "myData"),
    hx.Event("myOtherEvent", map[string]any{"fieldA": "keyA"}),
))
// Sets HX-Trigger header to `simpleOne, simpleTwo, {"myEvent":"myData","myOtherEvent":{"fieldA":"keyA"}}`

type HxHeaders

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

HxHeaders is a struct that contains the headers and status code to be returned to the client

This is helpful for using HTMX with a framework that doesn't implement the stdlib http.ResponseWriter

func BuildHeaders

func BuildHeaders(options ...HeaderOption) (headers *HxHeaders, err error)

BuildHeaders creates a new HxHeaders from the provided options.

It can be used to create a response helper for your own HTTP library.

Several libraries have already been implemented:

  • Echo: import github.com/stackus/hxgo/v4/hxecho
  • Fiber: import github.com/stackus/hxgo/v4/hxfiber
  • Gin: import github.com/stackus/hxgo/v4/hxgin

func (HxHeaders) Headers

func (r HxHeaders) Headers() map[string]string

type LocationProperties

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

func Location

func Location(path string) *LocationProperties

Location sets the HxLocation header on a response

This header is used for client-side redirection without a full page reload. Additional properties like LocationTarget can be specified for more complex behaviors.

More details, see: https://four.htmx.org/reference/headers/HX-Location

Simple redirection example:

	hx.Headers(w, hx.Location("/test"))
 // Sets HX-Location header to "/test"

Redirection with additional target example:

hx.Headers(w, hx.Location("/test").Target("#testdiv"))
// Sets HX-Location header to a JSON object: {"path":"/test","target":"#testdiv"}

func (*LocationProperties) Event

Event sets the 'event' property of the HxLocation response header.

More details: https://four.htmx.org/reference/headers/HX-Location

func (*LocationProperties) Headers

func (l *LocationProperties) Headers(headers map[string]string) *LocationProperties

Headers sets the 'headers' property of the HxLocation response header.

Accepts a map[string]string.

More details: https://four.htmx.org/reference/headers/HX-Location

func (*LocationProperties) Select

Select sets the 'select' property of the HxLocation response header.

More details: https://four.htmx.org/reference/headers/HX-Location

func (*LocationProperties) SelectOOB

func (l *LocationProperties) SelectOOB(sel string) *LocationProperties

SelectOOB sets the 'selectOOB' property of the HxLocation response header.

More details: https://four.htmx.org/reference/headers/HX-Location

func (*LocationProperties) Source

Source sets the 'source' property of the HxLocation response header.

More details: https://four.htmx.org/reference/headers/HX-Location

func (*LocationProperties) Swap

Swap sets the 'swap' property of the HxLocation response header.

Either a string or a Reswap constant can be used.

More details: https://four.htmx.org/reference/headers/HX-Location

func (*LocationProperties) Target

Target sets the 'target' property of the HxLocation response header.

More details: https://four.htmx.org/reference/headers/HX-Location

func (*LocationProperties) Transition

func (l *LocationProperties) Transition() *LocationProperties

Transition sets the 'transition' property of the HxLocation response header.

More details: https://four.htmx.org/reference/headers/HX-Location

func (*LocationProperties) Values

func (l *LocationProperties) Values(values any) *LocationProperties

Values sets the 'values' property of the HxLocation response header.

Accepts any type, but a map[string]any or a struct with JSON tags is recommended.

More details: https://four.htmx.org/reference/headers/HX-Location

type Redirect

type Redirect string

Redirect sets the HxRedirect header.

More details: https://four.htmx.org/reference/headers/HX-Redirect

It is used for client-side redirects that require a full page reload.

Use it for non-htmx endpoints or pages that require a full browser load.

For AJAX navigation inside an htmx application, send HxLocation with Location(path).

Example usage:

hx.Headers(w, hx.Redirect("/new-url-location"))
// Sets the HX-Redirect header to "/new-url-location".

type Reselect

type Reselect string

Reselect sets the HxReselect header.

More details: https://four.htmx.org/reference/headers/HX-Reselect

This option overrides which part of the response is used for swapping, replacing whatever hx-select was set on the triggering element.

Example usage:

hx.Headers(w, hx.Reselect("#new-target"))
// Sets the HX-Reselect header to "#new-target".

type Reswap

type Reswap string

Reswap overrides the swap style used when inserting the response, replacing whatever hx-swap was set on the triggering element.

The constants correspond to the different swap styles:

  • SwapInnerHtml : Replaces content inside element.
  • SwapOuterHtml : Replaces entire element.
  • SwapTextContent : Replaces the text content of the element, without parsing the response as HTML.
  • SwapBefore : Inserts content before element.
  • SwapPrepend : Inserts content as first child.
  • SwapAppend : Inserts content as last child.
  • SwapAfter : Inserts content after element.
  • SwapInnerMorph : Morphs content inside element, preserving state and focus.
  • SwapOuterMorph : Morphs entire element, preserving state and focus.
  • SwapOuterSync : Morphs the target’s attributes, then replaces its children.
  • SwapDelete : Removes element (ignores response content).
  • SwapNone : Doesn’t insert content.
  • SwapUpsert : Updates existing elements by ID and inserts new ones.

For more details, see: https://four.htmx.org/reference/attributes/hx-swap

HxReswap also takes additional modifiers, see: https://four.htmx.org/reference/attributes/hx-swap#modifiers

Simple usage:

hx.Headers(w, hx.Reswap("innerHTML"))
// Sets HX-Reswap header to `innerHTML`

Constant usage example (same as above):

hx.Headers(w, hx.SwapInnerHtml)
// Also sets HX-Reswap header to `innerHTML`

Constant usage example (with modifiers):

hx.Headers(w, hx.SwapInnerHtml.Swap(1*time.Second).Settle(2*time.Second))
// Sets HX-Reswap header to `innerHTML swap:1s settle:2s`
const (
	SwapInnerHtml   Reswap = "innerHTML"   // Replaces content inside element.
	SwapOuterHtml   Reswap = "outerHTML"   // Replaces entire element.
	SwapTextContent Reswap = "textContent" // Replaces the text content of the element, without parsing the response as HTML.
	SwapBefore      Reswap = "before"      // Inserts content before element.
	SwapPrepend     Reswap = "prepend"     // Inserts content as first child.
	SwapAppend      Reswap = "append"      // Inserts content as last child.
	SwapAfter       Reswap = "after"       // Inserts content after element.
	SwapInnerMorph  Reswap = "innerMorph"  // Morphs content inside element, preserving state and focus.
	SwapOuterMorph  Reswap = "outerMorph"  // Morphs entire element, preserving state and focus.
	SwapOuterSync   Reswap = "outerSync"   // Morphs the target’s attributes, then replaces its children.
	SwapDelete      Reswap = "delete"      // Removes element (ignores response content).
	SwapNone        Reswap = "none"        // Doesn’t insert content.
	SwapUpsert      Reswap = "upsert"      // Updates existing elements by ID and inserts new ones.
)

Reswap constants

func (Reswap) FocusScroll

func (s Reswap) FocusScroll(focus bool) *ReswapModifiers

FocusScroll (HxReswap header modifier) controls whether restoring focus after a swap scrolls the focused element into view.

More details: https://four.htmx.org/reference/attributes/hx-swap#focusscroll

Example usage:

hx.Headers(w, hx.SwapInnerHtml.FocusScroll(true))
// Sets HX-Reswap header to `innerHTML focusScroll:true

func (Reswap) IgnoreTitle

func (s Reswap) IgnoreTitle() *ReswapModifiers

IgnoreTitle (HxReswap header modifier) prevents updating the page <title>.

More details: https://four.htmx.org/reference/attributes/hx-swap#ignoretitle

Example usage:

hx.Headers(w, hx.SwapInnerHtml.IgnoreTitle())
// Sets HX-Reswap header to `innerHTML ignoreTitle:true`

func (Reswap) ScrollBottom

func (s Reswap) ScrollBottom(targets ...any) *ReswapModifiers

ScrollBottom (HxReswap header modifier) auto-scroll to the bottom of the swapped content, the window, or target.

More details: https://four.htmx.org/reference/attributes/hx-swap#scroll

Example usage:

hx.Headers(w, hx.SwapInnerHtml.ScrollBottom()
// Sets HX-Reswap header to `innerHTML scroll:bottom`
hx.Headers(w, hx.SwapInnerHtml.ScrollBottom(true)
// Sets HX-Reswap header to `innerHTML scroll:window:bottom`
hx.Headers(w, hx.SwapInnerHtml.ScrollBottom("#another-div"))
// Sets HX-Reswap header to `innerHTML scroll:bottom scrollTarget:"#another-div"`

func (Reswap) ScrollTop

func (s Reswap) ScrollTop(targets ...any) *ReswapModifiers

ScrollTop (HxReswap header modifier) auto-scroll to the top of the swapped content, the window, or target.

More details: https://four.htmx.org/reference/attributes/hx-swap#scroll

Example usage:

hx.Headers(w, hx.SwapInnerHtml.ScrollTop()
// Sets HX-Reswap header to `innerHTML scroll:top`
hx.Headers(w, hx.SwapInnerHtml.ScrollTop(true)
// Sets HX-Reswap header to `innerHTML scroll:window:top`
hx.Headers(w, hx.SwapInnerHtml.ScrollTop("#another-div"))
// Sets HX-Reswap header to `innerHTML scroll:top scrollTarget:"#another-div"`

func (Reswap) Settle

func (s Reswap) Settle(dur any) *ReswapModifiers

Settle (HxReswap header modifier) adds delay between the swap and the settle phase.

More details: https://four.htmx.org/reference/attributes/hx-swap#settle

Example usage:

hx.Headers(w, hx.SwapInnerHtml.Settle(1*time.Second))
// Sets HX-Reswap header to `innerHTML settle:1s`

func (Reswap) ShowBottom

func (s Reswap) ShowBottom(other ...string) *ReswapModifiers

ShowBottom (HxReswap header modifier) scrolls to show the bottom of the target or different element in viewport.

More details: https://four.htmx.org/reference/attributes/hx-swap#show

Example usage:

hx.Headers(w, hx.SwapInnerHtml.ShowBottom())
// Sets HX-Reswap header to `innerHTML show:bottom`
hx.Headers(w, hx.SwapInnerHtml.ShowBottom("#another-div"))
// Sets HX-Reswap header to `innerHTML show:bottom showTarget:"#another-div"`

func (Reswap) ShowNone

func (s Reswap) ShowNone() *ReswapModifiers

ShowNone (HxReswap header modifier) disables scrolling the viewport.

More details: https://four.htmx.org/reference/attributes/hx-swap#show

Example usage:

hx.Headers(w, hx.SwapInnerHtml.ShowNone())
// Sets HX-Reswap header to `innerHTML show:none`

func (Reswap) ShowTop

func (s Reswap) ShowTop(other ...string) *ReswapModifiers

ShowTop (HxReswap header modifier) scrolls to show the top of the target or different element in viewport.

More details: https://four.htmx.org/reference/attributes/hx-swap#show

Example usage:

hx.Headers(w, hx.SwapInnerHtml.ShowTop())
// Sets HX-Reswap header to `innerHTML show:top`
hx.Headers(w, hx.SwapInnerHtml.ShowTop("#another-div"))
// Sets HX-Reswap header to `innerHTML show:top showTarget:"#another-div"`

func (Reswap) Strip

func (s Reswap) Strip(strip bool) *ReswapModifiers

Strip (HxReswap header modifier) controls whether the response’s outer element is removed.

More details: https://four.htmx.org/reference/attributes/hx-swap#strip

Example usage:

hx.Headers(w, hx.SwapInnerHtml.Strip(true)
// Sets HX-Reswap header to `innerHTML strip:true`

func (Reswap) Swap

func (s Reswap) Swap(dur any) *ReswapModifiers

Swap (HxReswap header modifier) adds delay before swap.

More details: https://four.htmx.org/reference/attributes/hx-swap#swap

Example usage:

hx.Headers(w, hx.SwapInnerHtml.Swap(1*time.Second))
// Sets HX-Reswap header to `innerHTML swap:1s`
hx.Headers(w, hx.SwapInnerHtml.Swap("1s"))
// Sets HX-Reswap header to `innerHTML swap:1s`

func (Reswap) SwapEmpty

func (s Reswap) SwapEmpty(swapEmpty bool) *ReswapModifiers

SwapEmpty (HxReswap header modifier) controls whether the response’s outer element is removed.

More details: https://four.htmx.org/reference/attributes/hx-swap#swapEmpty

Example usage:

hx.Headers(w, hx.SwapInnerHtml.SwapEmpty(true)
// Sets HX-Reswap header to `innerHTML swapEmpty:true`

func (Reswap) Target

func (s Reswap) Target(target string) *ReswapModifiers

Target (HxReswap header modifier) sets the swap target.

More details: https://four.htmx.org/reference/attributes/hx-swap#target

Example usage:

hx.Headers(w, hx.SwapInnerHtml.Target("#some-target")
// Sets HX-Reswap header to `innerHTML target:"#some-target"`

func (Reswap) Transition

func (s Reswap) Transition() *ReswapModifiers

Transition (HxReswap header modifier) enables View Transitions API for smooth page transitions.

More details: https://four.htmx.org/reference/attributes/hx-swap#transition

Example usage:

hx.Headers(w, hx.SwapInnerHtml.Transition())
// Sets HX-Reswap header to `innerHTML transition:true`

type ReswapModifiers

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

ReswapModifiers overrides the swap style used when inserting the response, replacing whatever hx-swap was set on the triggering element.

For more details, see: https://four.htmx.org/reference/attributes/hx-swap

HxReswap also takes additional modifiers, see: https://four.htmx.org/reference/attributes/hx-swap#modifiers

Simple usage:

hx.Headers(w, hx.Reswap("innerHTML"))
// Sets HX-Reswap header to `innerHTML`

Constant usage example (same as above):

hx.Headers(w, hx.SwapInnerHtml)
// Also sets HX-Reswap header to `innerHTML`

Constant usage example (with modifiers):

hx.Headers(w, hx.SwapInnerHtml.Swap(1*time.Second).Settle(2*time.Second))
// Sets HX-Reswap header to `innerHTML swap:1s settle:2s`

func (*ReswapModifiers) FocusScroll

func (r *ReswapModifiers) FocusScroll(focus bool) *ReswapModifiers

FocusScroll (HxReswap header modifier) controls whether restoring focus after a swap scrolls the focused element into view.

More details: https://four.htmx.org/reference/attributes/hx-swap#focusscroll

Example usage:

hx.Headers(w, hx.SwapInnerHtml.Transition().FocusScroll(true))
// Sets HX-Reswap header to `innerHTML transition:true focusScroll:true`

func (*ReswapModifiers) IgnoreTitle

func (r *ReswapModifiers) IgnoreTitle() *ReswapModifiers

IgnoreTitle (HxReswap header modifier) prevents updating the page <title>.

More details: https://four.htmx.org/reference/attributes/hx-swap#ignoretitle

Example usage:

hx.Headers(w, hx.SwapInnerHtml.Transition().IgnoreTitle())
// Sets HX-Reswap header to `innerHTML transition:true ignoreTitle:true`

func (*ReswapModifiers) ScrollBottom

func (r *ReswapModifiers) ScrollBottom(targets ...any) *ReswapModifiers

ScrollBottom (HxReswap header modifier) auto-scroll to the bottom of the swapped content, the window, or target.

More details: https://four.htmx.org/reference/attributes/hx-swap#scroll

Example usage:

hx.Headers(w, hx.SwapInnerHtml.Transition().ScrollBottom()
// Sets HX-Reswap header to `innerHTML transition:true scroll:bottom`
hx.Headers(w, hx.SwapInnerHtml.Transition().ScrollBottom(true)
// Sets HX-Reswap header to `innerHTML transition:true scroll:window:bottom`
hx.Headers(w, hx.SwapInnerHtml.Transition().ScrollBottom("#another-div"))
// Sets HX-Reswap header to `innerHTML transition:true scroll:bottom scrollTarget:"#another-div"`

func (*ReswapModifiers) ScrollTop

func (r *ReswapModifiers) ScrollTop(targets ...any) *ReswapModifiers

ScrollTop (HxReswap header modifier) auto-scroll to the top of the swapped content, the window, or target.

More details: https://four.htmx.org/reference/attributes/hx-swap#scroll

Example usage:

hx.Headers(w, hx.SwapInnerHtml.Transition().ScrollTop()
// Sets HX-Reswap header to `innerHTML transition:true scroll:top`
hx.Headers(w, hx.SwapInnerHtml.Transition().ScrollTop(true)
// Sets HX-Reswap header to `innerHTML transition:true scroll:window:top`
hx.Headers(w, hx.SwapInnerHtml.Transition().ScrollTop("#another-div"))
// Sets HX-Reswap header to `innerHTML transition:true scroll:top scrollTarget:"#another-div"`

func (*ReswapModifiers) Settle

func (r *ReswapModifiers) Settle(dur any) *ReswapModifiers

Settle (HxReswap header modifier) adds delay between the swap and the settle phase.

More details: https://four.htmx.org/reference/attributes/hx-swap#settle

Example usage:

hx.Headers(w, hx.SwapInnerHtml.Transition().Settle(1*time.Second))
// Sets HX-Reswap header to `innerHTML transition:true settle:1s`

func (*ReswapModifiers) ShowBottom

func (r *ReswapModifiers) ShowBottom(other ...string) *ReswapModifiers

ShowBottom (HxReswap header modifier) scrolls to show the bottom of the target or different element in viewport.

More details: https://four.htmx.org/reference/attributes/hx-swap#show

Example usage:

hx.Headers(w, hx.SwapInnerHtml.Transition().ShowBottom())
// Sets HX-Reswap header to `innerHTML transition:true show:bottom`
hx.Headers(w, hx.SwapInnerHtml.Transition().ShowBottom("#another-div"))
// Sets HX-Reswap header to `innerHTML transition:true show:bottom showTarget:"#another-div"`

func (*ReswapModifiers) ShowNone

func (r *ReswapModifiers) ShowNone() *ReswapModifiers

ShowNone (HxReswap header modifier) disables scrolling the viewport.

More details: https://four.htmx.org/reference/attributes/hx-swap#show

Example usage:

hx.Headers(w, hx.SwapInnerHtml.Transition().ShowNone())
// Sets HX-Reswap header to `innerHTML transition:true show:none`

func (*ReswapModifiers) ShowTop

func (r *ReswapModifiers) ShowTop(other ...string) *ReswapModifiers

ShowTop (HxReswap header modifier) scrolls to show the top of the target or different element in viewport.

More details: https://four.htmx.org/reference/attributes/hx-swap#show

Example usage:

hx.Headers(w, hx.SwapInnerHtml.Transition().ShowTop())
// Sets HX-Reswap header to `innerHTML transition:true show:top`
hx.Headers(w, hx.SwapInnerHtml.Transition().ShowTop("#another-div"))
// Sets HX-Reswap header to `innerHTML transition:true show:top showTarget:"#another-div"`

func (*ReswapModifiers) String

func (r *ReswapModifiers) String() string

func (*ReswapModifiers) Strip

func (r *ReswapModifiers) Strip(strip bool) *ReswapModifiers

Strip (HxReswap header modifier) controls whether the response’s outer element is removed.

More details: https://four.htmx.org/reference/attributes/hx-swap#strip

Example usage:

hx.Headers(w, hx.SwapInnerHtml.Transition().Strip(true)
// Sets HX-Reswap header to `innerHTML transition:true strip:true`

func (*ReswapModifiers) Swap

func (r *ReswapModifiers) Swap(dur any) *ReswapModifiers

Swap (HxReswap header modifier) adds delay before swap.

More details: https://four.htmx.org/reference/attributes/hx-swap#swap

Example usage:

hx.Headers(w, hx.SwapInnerHtml.Transition().Swap(1*time.Second))
// Sets HX-Reswap header to `innerHTML transition:true swap:1s`
hx.Headers(w, hx.SwapInnerHtml.Transition().Swap("1s))
// Sets HX-Reswap header to `innerHTML transition:true swap:1s`

func (*ReswapModifiers) SwapEmpty

func (r *ReswapModifiers) SwapEmpty(swapEmpty bool) *ReswapModifiers

SwapEmpty (HxReswap header modifier) controls whether the response’s outer element is removed.

More details: https://four.htmx.org/reference/attributes/hx-swap#swapEmpty

Example usage:

hx.Headers(w, hx.SwapInnerHtml.Transition().SwapEmpty(true)
// Sets HX-Reswap header to `innerHTML transition:true swapEmpty:true`

func (*ReswapModifiers) Target

func (r *ReswapModifiers) Target(target string) *ReswapModifiers

Target (HxReswap header modifier) sets the swap target.

More details: https://four.htmx.org/reference/attributes/hx-swap#target

Example usage:

hx.Headers(w, hx.SwapInnerHtml.Transition().Target("#some-target")
// Sets HX-Reswap header to `innerHTML transition:true target:"#some-target"`

func (*ReswapModifiers) Transition

func (r *ReswapModifiers) Transition() *ReswapModifiers

Transition (HxReswap header modifier) enables View Transitions API for smooth page transitions.

More details: https://four.htmx.org/reference/attributes/hx-swap#transition

Example usage:

hx.Headers(w, hx.SwapInnerHtml.Swap(1*time.Second).Transition())
// Sets HX-Reswap header to `innerHTML swap:1s transition:true`

type Retarget

type Retarget string

Retarget sets the HxRetarget header.

More details: https://four.htmx.org/reference/headers/HX-Retarget

This option specifies a new CSS selector to redirect the content update to a different element on the page.

Example usage:

hx.Headers(w, hx.Retarget("#new-target"))
// Sets the HX-Retarget header to "#new-target".

type TriggerEvent

type TriggerEvent func() ([]byte, error)

func Event

func Event(name string, data ...any) TriggerEvent

Event creates an event to pass into the Trigger() function.

Simple named event:

hx.Event("myEvent")
// Returns {"myEvent":null}

Named event with string data:

hx.Event("myEvent", "myData")
// Returns {"myEvent":"myData"}

Named event with multiple data items (treated like an array):

hx.Event("myEvent", "myData1", "myData2")
// Returns {"myEvent":["myData1","myData2"]}

Named event with a struct or map (treated like an object):

hx.Event("myEvent", map[string]string{"myKey": "myValue"})
// Returns {"myEvent":{"myKey":"myValue"}}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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