htmx

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2026 License: MIT Imports: 5 Imported by: 0

README

HTMX Package

The htmx package provides seamless HTMX integration for ForgeUI, enabling modern, interactive user interfaces with server-side rendering.

Features

  • 🚀 Full HTMX Support: Complete attribute helpers for all HTMX features
  • 🎯 Type-Safe: Go functions for all HTMX attributes
  • 🔄 Request Detection: Server-side helpers to detect and handle HTMX requests
  • 📡 Response Control: Programmatic control over HTMX response headers
  • Progressive Enhancement: Build with hx-boost for seamless navigation
  • 🎨 Loading States: Built-in indicator and disabled element support

Installation

go get github.com/xraph/forgeui/htmx

Quick Start

1. Load HTMX

html.Head(
    htmx.Scripts(),
    htmx.IndicatorCSS(),
)

2. Add HTMX Attributes

html.Button(
    htmx.HxGet("/api/users"),
    htmx.HxTarget("#user-list"),
    htmx.HxSwap("innerHTML"),
    g.Text("Load Users"),
)

3. Server-Side Handling

func handler(w http.ResponseWriter, r *http.Request) {
    if htmx.IsHTMX(r) {
        // Return partial HTML
        renderUserList(w, users)
    } else {
        // Return full page
        renderFullPage(w, users)
    }
}

HTTP Methods

Basic Requests

// GET request
html.Button(
    htmx.HxGet("/api/data"),
    htmx.HxTarget("#results"),
)

// POST request
html.Form(
    htmx.HxPost("/api/submit"),
    // form fields...
)

// Other methods
htmx.HxPut("/api/update/123")
htmx.HxPatch("/api/partial-update/123")
htmx.HxDelete("/api/delete/123")

Targeting & Swapping

Target Selection

htmx.HxTarget("#container")     // CSS selector
htmx.HxTarget("this")            // Current element
htmx.HxTarget("closest div")     // Closest parent div
htmx.HxTarget("next .item")      // Next sibling with class
htmx.HxTarget("previous input")  // Previous sibling input

Swap Strategies

// Replace strategies
htmx.HxSwapInnerHTML()    // Replace inner HTML (default)
htmx.HxSwapOuterHTML()    // Replace entire element

// Insert strategies
htmx.HxSwapBeforeBegin()  // Insert before element
htmx.HxSwapAfterBegin()   // Insert as first child
htmx.HxSwapBeforeEnd()    // Insert as last child
htmx.HxSwapAfterEnd()     // Insert after element

// Special strategies
htmx.HxSwapDelete()       // Delete target
htmx.HxSwapNone()         // Don't swap

Triggers

Basic Triggers

html.Input(
    htmx.HxTriggerChange(),      // On change event
    htmx.HxGet("/search"),
)

html.Button(
    htmx.HxTriggerClick(),       // On click event
    htmx.HxPost("/action"),
)

Advanced Triggers

// Debouncing (wait for pause in events)
html.Input(
    htmx.HxTriggerDebounce("keyup", "500ms"),
    htmx.HxGet("/search"),
)

// Throttling (limit event frequency)
html.Div(
    htmx.HxTriggerThrottle("scroll", "1s"),
    htmx.HxGet("/more"),
)

// On load
html.Div(
    htmx.HxTriggerLoad(),
    htmx.HxGet("/initial-data"),
)

// When revealed (scrolled into view)
html.Div(
    htmx.HxTriggerRevealed(),
    htmx.HxGet("/lazy-load"),
)

// Fire only once
html.Button(
    htmx.HxTriggerOnce("click"),
    htmx.HxPost("/init"),
)

// Polling
html.Div(
    htmx.HxTriggerEvery("2s"),
    htmx.HxGet("/status"),
)

Loading States

Indicators

html.Button(
    htmx.HxPost("/submit"),
    htmx.HxIndicator("#spinner"),
    g.Text("Submit"),
)

html.Div(
    html.ID("spinner"),
    html.Class("htmx-indicator"),
    icons.Loader(icons.WithClass("animate-spin")),
)

Disabled Elements

html.Button(
    htmx.HxPost("/submit"),
    htmx.HxDisabledElt("this"),  // Disable button during request
    g.Text("Submit"),
)

Request Synchronization

// Drop subsequent requests
html.Input(
    htmx.HxGet("/search"),
    htmx.HxSync("this", "drop"),
)

// Abort current request
html.Input(
    htmx.HxGet("/search"),
    htmx.HxSync("this", "abort"),
)

// Replace current request
html.Input(
    htmx.HxGet("/search"),
    htmx.HxSync("this", "replace"),
)

Progressive Enhancement

Boosted Navigation

// Boost all links in a container
html.Nav(
    htmx.HxBoost(true),
    html.A(html.Href("/page1"), g.Text("Page 1")),
    html.A(html.Href("/page2"), g.Text("Page 2")),
)

History Management

// Push URL to history
html.Button(
    htmx.HxGet("/page/2"),
    htmx.HxPushURL(true),
    g.Text("Next Page"),
)

// Replace URL in history
html.Button(
    htmx.HxGet("/search?q=test"),
    htmx.HxReplaceURL(true),
    g.Text("Search"),
)

// Custom path in history
html.Button(
    htmx.HxGet("/api/page/2"),
    htmx.HxPushURLWithPath("/page/2"),
    g.Text("Next"),
)

Server-Side

Request Detection

func handler(w http.ResponseWriter, r *http.Request) {
    // Check if request is from HTMX
    if htmx.IsHTMX(r) {
        // Return partial HTML
    }

    // Check if request is boosted
    if htmx.IsHTMXBoosted(r) {
        // Handle boosted request
    }

    // Get request details
    target := htmx.HTMXTarget(r)        // Target element
    trigger := htmx.HTMXTrigger(r)      // Triggering element
    prompt := htmx.HTMXPrompt(r)        // Prompt response
    currentURL := htmx.HTMXCurrentURL(r) // Current URL
}

Response Headers

// Trigger client-side events
htmx.SetHTMXTrigger(w, map[string]any{
    "showMessage": map[string]string{
        "level": "success",
        "text": "Saved successfully!",
    },
})

// Simple event
htmx.TriggerEvent(w, "refresh")

// Event with details
htmx.TriggerEventWithDetail(w, "itemUpdated", map[string]any{
    "id": 123,
})

// Client-side redirect
htmx.SetHTMXRedirect(w, "/login")

// Full page refresh
htmx.SetHTMXRefresh(w)

// Update URL
htmx.SetHTMXPushURL(w, "/new-url")
htmx.SetHTMXReplaceURL(w, "/current-url")

// Change swap target/strategy
htmx.SetHTMXRetarget(w, "#different-element")
htmx.SetHTMXReswap(w, "outerHTML")

Response Header Helper

htmx.SetResponseHeaders(w, htmx.ResponseHeaders{
    Trigger: map[string]any{
        "showToast": map[string]string{"msg": "Success!"},
    },
    Refresh: false,
    PushURL: "/page/2",
})

Request Configuration

Custom Headers

html.Button(
    htmx.HxPost("/api/data"),
    htmx.HxHeaders(map[string]string{
        "X-API-Key": "secret",
        "X-Request-ID": "123",
    }),
)

Extra Values

html.Button(
    htmx.HxPost("/api/data"),
    htmx.HxVals(map[string]any{
        "category": "urgent",
        "priority": 1,
    }),
)

// JavaScript values
html.Button(
    htmx.HxPost("/api/data"),
    htmx.HxValsJS("js:{timestamp: Date.now()}"),
)

Parameter Filtering

// Include only specific params
html.Form(
    htmx.HxPost("/submit"),
    htmx.HxParams("email,name"),
)

// Include all params
htmx.HxParams("*")

// Include no params
htmx.HxParams("none")

// Exclude specific params
htmx.HxParams("not password,token")

Confirmation & Prompts

// Confirmation dialog
html.Button(
    htmx.HxDelete("/api/item/123"),
    htmx.HxConfirm("Are you sure you want to delete this?"),
    g.Text("Delete"),
)

// Prompt for input
html.Button(
    htmx.HxPost("/api/comment"),
    htmx.HxPrompt("Enter your comment"),
    g.Text("Add Comment"),
)

Extensions

Loading Extensions

// Single extension
html.Head(
    htmx.Scripts(),
    htmx.ExtensionScript(htmx.ExtensionSSE),
)

// Multiple extensions
html.Head(
    g.Group(htmx.ScriptsWithExtensions(
        htmx.ExtensionSSE,
        htmx.ExtensionWebSockets,
        htmx.ExtensionJSONEnc,
    )),
)

Available Extensions

  • ExtensionSSE - Server-Sent Events
  • ExtensionWebSockets - WebSocket support
  • ExtensionClassTools - Advanced class manipulation
  • ExtensionPreload - Preload content on hover
  • ExtensionHeadSupport - Support for head merging
  • ExtensionResponseTargets - Multiple targets from one response
  • ExtensionDebug - Debug HTMX requests
  • ExtensionJSONEnc - JSON encoding for requests
  • ExtensionMethodOverride - HTTP method override
  • ExtensionMultiSwap - Multiple swaps in one response

Using Extensions

html.Div(
    htmx.HxExt("json-enc"),
    htmx.HxPost("/api/data"),
    // Request body will be JSON encoded
)

Advanced Features

Out-of-Band Swaps

html.Button(
    htmx.HxGet("/data"),
    htmx.HxSelectOOB("#notifications, #messages"),
)

Response Filtering

html.Button(
    htmx.HxGet("/full-page"),
    htmx.HxSelect("#content"),      // Select from response
    htmx.HxTarget("#main"),         // Insert into target
)

Element Preservation

// Preserve element during swaps
html.Video(
    htmx.HxPreserve(),
    html.Src("/video.mp4"),
)

File Uploads

html.Form(
    htmx.HxPost("/upload"),
    htmx.HxEncoding("multipart/form-data"),
    html.Input(html.Type("file"), html.Name("file")),
)

Validation

html.Input(
    html.Type("email"),
    html.Required(),
    htmx.HxValidate(true),  // Force validation before submit
)

CSS Utilities

Cloak (Hide Until Loaded)

html.Head(
    htmx.CloakCSS(),
)

html.Div(
    htmx.HxCloak(),
    htmx.HxGet("/content"),
    htmx.HxTriggerLoad(),
)

Indicator Styles

html.Head(
    htmx.IndicatorCSS(),
)

Best Practices

1. Progressive Enhancement

Start with working server-rendered forms, then enhance with HTMX:

html.Form(
    html.Action("/submit"),
    html.Method("POST"),
    htmx.HxPost("/submit"),  // HTMX enhancement
    htmx.HxTarget("#results"),
    // form fields...
)

2. Proper Response Types

func handler(w http.ResponseWriter, r *http.Request) {
    if htmx.IsHTMX(r) {
        // Return only what's needed
        w.Write([]byte("<div>Partial</div>"))
    } else {
        // Return full page for non-HTMX browsers
        renderFullPage(w)
    }
}

3. Loading States

Always provide feedback during requests:

html.Button(
    htmx.HxPost("/submit"),
    htmx.HxIndicator("#spinner"),
    htmx.HxDisabledElt("this"),
    g.Text("Submit"),
)

4. Error Handling

Handle errors gracefully:

func handler(w http.ResponseWriter, r *http.Request) {
    if err := process(); err != nil {
        htmx.SetHTMXTrigger(w, map[string]any{
            "showError": map[string]string{
                "message": err.Error(),
            },
        })
        w.WriteHeader(http.StatusBadRequest)
        return
    }
    // success...
}

Examples

See the example/ directory for complete working examples including:

  • Form submissions
  • Infinite scroll
  • Search with debouncing
  • Modal dialogs
  • Real-time updates

Resources

Performance Tips

  1. Use hx-sync for search inputs to prevent race conditions
  2. Use hx-trigger modifiers (debounce/throttle) to reduce server requests
  3. Cache responses server-side for common requests
  4. Use out-of-band swaps to update multiple elements efficiently
  5. Implement proper loading states for better UX

Documentation

Overview

Package htmx provides HTMX integration for ForgeUI.

HTMX allows you to access AJAX, CSS Transitions, WebSockets and Server Sent Events directly in HTML, using attributes. This enables building modern, interactive user interfaces while keeping your application architecture simple and maintainable.

Basic Usage

Add HTMX attributes to your HTML elements:

html.Button(
    htmx.HxGet("/api/users"),
    htmx.HxTarget("#user-list"),
    htmx.HxSwap("innerHTML"),
    g.Text("Load Users"),
)

HTTP Methods

HTMX supports all standard HTTP methods:

htmx.HxGet("/api/data")      // GET request
htmx.HxPost("/api/create")   // POST request
htmx.HxPut("/api/update/1")  // PUT request
htmx.HxPatch("/api/patch/1") // PATCH request
htmx.HxDelete("/api/del/1")  // DELETE request

Targeting and Swapping

Control where and how responses are inserted:

html.Button(
    htmx.HxGet("/content"),
    htmx.HxTarget("#container"),
    htmx.HxSwap("beforeend"),  // Append to container
)

Available swap strategies:

  • innerHTML (default): Replace inner HTML
  • outerHTML: Replace entire element
  • beforebegin: Insert before element
  • afterbegin: Insert as first child
  • beforeend: Insert as last child
  • afterend: Insert after element
  • delete: Delete the target
  • none: Don't swap

Triggers

Specify when requests are made:

html.Input(
    htmx.HxGet("/search"),
    htmx.HxTriggerDebounce("keyup", "500ms"),
    htmx.HxTarget("#results"),
)

Common triggers:

  • click: On element click
  • change: On input change
  • submit: On form submit
  • load: When element loads
  • revealed: When scrolled into view
  • intersect: When element intersects viewport

Server-Side Usage

Detect HTMX requests and respond appropriately:

func handler(w http.ResponseWriter, r *http.Request) {
    if htmx.IsHTMX(r) {
        // Return partial HTML
        renderPartial(w, data)
    } else {
        // Return full page
        renderFullPage(w, data)
    }
}

Response Headers

Control client behavior with response headers:

htmx.SetHTMXTrigger(w, map[string]any{
    "showMessage": map[string]string{
        "level": "success",
        "text": "Item saved!",
    },
})

Available response headers:

  • HX-Trigger: Trigger client-side events
  • HX-Redirect: Perform client-side redirect
  • HX-Refresh: Force full page refresh
  • HX-Retarget: Change swap target
  • HX-Reswap: Change swap strategy
  • HX-Push-Url: Update browser URL
  • HX-Replace-Url: Replace browser URL

Progressive Enhancement

Use hx-boost for seamless navigation:

html.Div(
    htmx.HxBoost(true),
    html.A(html.Href("/page1"), g.Text("Page 1")),
    html.A(html.Href("/page2"), g.Text("Page 2")),
)

Loading States

Show indicators during requests:

html.Button(
    htmx.HxPost("/api/submit"),
    htmx.HxIndicator("#spinner"),
    htmx.HxDisabledElt("this"),
    g.Text("Submit"),
)
html.Div(
    html.ID("spinner"),
    html.Class("htmx-indicator"),
    g.Text("Loading..."),
)

Extensions

Load HTMX extensions for additional functionality:

htmx.ScriptsWithExtensions(
    htmx.ExtensionSSE,
    htmx.ExtensionWebSockets,
)

Index

Constants

View Source
const (
	ExtensionSSE             = "sse"
	ExtensionWebSockets      = "ws"
	ExtensionClassTools      = "class-tools"
	ExtensionPreload         = "preload"
	ExtensionHeadSupport     = "head-support"
	ExtensionResponseTargets = "response-targets"
	ExtensionDebug           = "debug"
	ExtensionEventHeader     = "event-header"
	ExtensionIncludeVals     = "include-vals"
	ExtensionJSONEnc         = "json-enc"
	ExtensionMethodOverride  = "method-override"
	ExtensionMorphdom        = "morphdom-swap"
	ExtensionMultiSwap       = "multi-swap"
	ExtensionPathDeps        = "path-deps"
	ExtensionRestoreOnError  = "restored"
)

HTMX extension names

View Source
const DefaultVersion = "2.0.3"

DefaultVersion is the default HTMX version.

Variables

This section is empty.

Functions

func CloakCSS

func CloakCSS() g.Node

CloakCSS returns a style tag that prevents flash of unstyled content for elements with hx-cloak attribute.

Add this to your page head and use HxCloak() on elements that should be hidden until HTMX initializes.

Example:

html.Head(
    htmx.CloakCSS(),
)
html.Body(
    html.Div(
        htmx.HxCloak(),
        htmx.HxGet("/content"),
        htmx.HxTriggerLoad(),
    ),
)

func ConfigMeta

func ConfigMeta(config map[string]string) []g.Node

ConfigMeta returns meta tags for HTMX configuration.

Example:

html.Head(
    htmx.ConfigMeta(map[string]string{
        "defaultSwapStyle": "outerHTML",
        "timeout": "5000",
    }),
)

func ExtensionScript

func ExtensionScript(extension string) g.Node

ExtensionScript returns a script tag for a specific HTMX extension.

Example:

html.Head(
    htmx.Scripts(),
    htmx.ExtensionScript(htmx.ExtensionSSE),
)

func HTMXCurrentURL

func HTMXCurrentURL(r *http.Request) string

HTMXCurrentURL gets the current URL of the browser when the HTMX request was made.

Example:

currentURL := htmx.HTMXCurrentURL(r)

func HTMXHistoryRestoreRequest

func HTMXHistoryRestoreRequest(r *http.Request) bool

HTMXHistoryRestoreRequest checks if this request is for history restoration after a miss in the local history cache.

Example:

if htmx.HTMXHistoryRestoreRequest(r) {
    // Handle history restoration
}

func HTMXPrompt

func HTMXPrompt(r *http.Request) string

HTMXPrompt gets the user response to an hx-prompt.

Example:

if prompt := htmx.HTMXPrompt(r); prompt != "" {
    // Use the prompt value
    processComment(prompt)
}

func HTMXTarget

func HTMXTarget(r *http.Request) string

HTMXTarget gets the ID of the target element if it exists.

Example:

targetID := htmx.HTMXTarget(r)

func HTMXTrigger

func HTMXTrigger(r *http.Request) string

HTMXTrigger gets the ID of the triggered element if it exists.

Example:

triggerID := htmx.HTMXTrigger(r)

func HTMXTriggerName

func HTMXTriggerName(r *http.Request) string

HTMXTriggerName gets the name of the triggered element if it exists.

Example:

triggerName := htmx.HTMXTriggerName(r)

func HxBoost

func HxBoost(enabled bool) g.Node

HxBoost creates an hx-boost attribute for progressive enhancement of links/forms.

Example:

html.Div(
    htmx.HxBoost(true),
    html.A(html.Href("/page1"), g.Text("Page 1")),
    html.A(html.Href("/page2"), g.Text("Page 2")),
)

func HxCloak

func HxCloak() g.Node

HxCloak creates an hx-cloak attribute to hide elements until HTMX processes them.

Example:

html.Div(
    htmx.HxCloak(),
    htmx.HxGet("/content"),
    htmx.HxTriggerLoad(),
)

func HxConfirm

func HxConfirm(message string) g.Node

HxConfirm creates an hx-confirm attribute for confirmation dialogs.

Example:

html.Button(
    htmx.HxDelete("/api/item/123"),
    htmx.HxConfirm("Are you sure you want to delete this item?"),
    g.Text("Delete"),
)

func HxDelete

func HxDelete(url string) g.Node

HxDelete creates an hx-delete attribute for DELETE requests.

Example:

html.Button(
    htmx.HxDelete("/api/delete/123"),
    htmx.HxConfirm("Are you sure?"),
    g.Text("Delete"),
)

func HxDisabledElt

func HxDisabledElt(selector string) g.Node

HxDisabledElt creates an hx-disabled-elt attribute to disable elements during requests.

Example:

html.Button(
    htmx.HxPost("/api/submit"),
    htmx.HxDisabledElt("this"),
    g.Text("Submit"),
)

func HxDisinherit

func HxDisinherit(attributes string) g.Node

HxDisinherit creates an hx-disinherit attribute that prevents inheritance of HTMX attributes from parent elements.

Example:

html.Div(
    htmx.HxDisinherit("hx-select hx-get"),
    // child elements won't inherit hx-select or hx-get
)

func HxEncoding

func HxEncoding(encoding string) g.Node

HxEncoding creates an hx-encoding attribute to set request encoding.

Example:

html.Form(
    htmx.HxPost("/api/upload"),
    htmx.HxEncoding("multipart/form-data"),
    // file input...
)

func HxExt

func HxExt(extension string) g.Node

HxExt creates an hx-ext attribute to load HTMX extensions.

Example:

html.Div(
    htmx.HxExt("json-enc"),
    htmx.HxPost("/api/data"),
)

func HxGet

func HxGet(url string) g.Node

HxGet creates an hx-get attribute for GET requests.

Example:

html.Button(
    htmx.HxGet("/api/data"),
    g.Text("Load Data"),
)

func HxHeaders

func HxHeaders(headers map[string]string) g.Node

HxHeaders creates an hx-headers attribute for custom headers.

Example:

html.Button(
    htmx.HxPost("/api/data"),
    htmx.HxHeaders(map[string]string{
        "X-API-Key": "secret",
    }),
    g.Text("Submit"),
)

func HxHistory

func HxHistory(enabled bool) g.Node

HxHistory creates an hx-history attribute to control history behavior.

Example:

html.Div(
    htmx.HxHistory(false),
    htmx.HxBoost(true),
    // links won't be added to history
)

func HxInclude

func HxInclude(selector string) g.Node

HxInclude creates an hx-include attribute to include additional elements in requests.

Example:

html.Button(
    htmx.HxPost("/api/submit"),
    htmx.HxInclude("#extra-data"),
    g.Text("Submit"),
)

func HxIndicator

func HxIndicator(selector string) g.Node

HxIndicator creates an hx-indicator attribute to specify a loading indicator.

Example:

html.Button(
    htmx.HxGet("/api/slow"),
    htmx.HxIndicator("#spinner"),
    g.Text("Load"),
)
html.Div(
    html.ID("spinner"),
    html.Class("htmx-indicator"),
    g.Text("Loading..."),
)

func HxParams

func HxParams(params string) g.Node

HxParams creates an hx-params attribute to filter parameters.

Values:

  • "*": Include all parameters (default)
  • "none": Include no parameters
  • "param1,param2": Include only specified parameters
  • "not param1,param2": Include all except specified parameters

Example:

html.Form(
    htmx.HxPost("/api/submit"),
    htmx.HxParams("email,name"),
    // form fields...
)

func HxPatch

func HxPatch(url string) g.Node

HxPatch creates an hx-patch attribute for PATCH requests.

Example:

html.Button(
    htmx.HxPatch("/api/partial-update/123"),
    g.Text("Patch"),
)

func HxPost

func HxPost(url string) g.Node

HxPost creates an hx-post attribute for POST requests.

Example:

html.Form(
    htmx.HxPost("/api/submit"),
    // form fields...
)

func HxPreserve

func HxPreserve(enabled bool) g.Node

HxPreserve creates an hx-preserve attribute to preserve elements across requests.

Example:

html.Video(
    htmx.HxPreserve(true),
    html.Src("/video.mp4"),
)

func HxPrompt

func HxPrompt(message string) g.Node

HxPrompt creates an hx-prompt attribute for user input.

Example:

html.Button(
    htmx.HxPost("/api/comment"),
    htmx.HxPrompt("Enter your comment"),
    g.Text("Add Comment"),
)

func HxPushURL

func HxPushURL(enabled bool) g.Node

HxPushURL creates an hx-push-url attribute for history management.

Example:

html.Button(
    htmx.HxGet("/page/2"),
    htmx.HxPushURL(true),
    g.Text("Next Page"),
)

func HxPushURLWithPath

func HxPushURLWithPath(path string) g.Node

HxPushURLWithPath creates an hx-push-url attribute with a custom path.

Example:

html.Button(
    htmx.HxGet("/api/page/2"),
    htmx.HxPushURLWithPath("/page/2"),
    g.Text("Next Page"),
)

func HxPut

func HxPut(url string) g.Node

HxPut creates an hx-put attribute for PUT requests.

Example:

html.Button(
    htmx.HxPut("/api/update/123"),
    g.Text("Update"),
)

func HxReplaceURL

func HxReplaceURL(enabled bool) g.Node

HxReplaceURL creates an hx-replace-url attribute to replace the current URL.

Example:

html.Button(
    htmx.HxGet("/search?q=test"),
    htmx.HxReplaceURL(true),
    g.Text("Search"),
)

func HxReplaceURLWithPath

func HxReplaceURLWithPath(path string) g.Node

HxReplaceURLWithPath creates an hx-replace-url attribute with a custom path.

func HxSelect

func HxSelect(selector string) g.Node

HxSelect creates an hx-select attribute for response filtering.

Example:

html.Button(
    htmx.HxGet("/full-page"),
    htmx.HxSelect("#content"),
    htmx.HxTarget("#main"),
    g.Text("Load Content"),
)

func HxSelectOOB

func HxSelectOOB(selector string) g.Node

HxSelectOOB creates an hx-select-oob attribute for out-of-band swapping.

Example:

htmx.HxSelectOOB("#notifications, #messages")

func HxSwap

func HxSwap(strategy string) g.Node

HxSwap creates an hx-swap attribute with a swap strategy.

Strategies:

  • innerHTML (default): Replace the inner html of the target element
  • outerHTML: Replace the entire target element
  • beforebegin: Insert before the target element
  • afterbegin: Insert before the first child of the target element
  • beforeend: Insert after the last child of the target element
  • afterend: Insert after the target element
  • delete: Deletes the target element regardless of the response
  • none: Does not append content

Example:

html.Button(
    htmx.HxGet("/api/item"),
    htmx.HxSwap("outerHTML"),
    g.Text("Replace"),
)

func HxSwapAfterBegin

func HxSwapAfterBegin() g.Node

HxSwapAfterBegin creates an hx-swap="afterbegin" attribute.

func HxSwapAfterEnd

func HxSwapAfterEnd() g.Node

HxSwapAfterEnd creates an hx-swap="afterend" attribute.

func HxSwapBeforeBegin

func HxSwapBeforeBegin() g.Node

HxSwapBeforeBegin creates an hx-swap="beforebegin" attribute.

func HxSwapBeforeEnd

func HxSwapBeforeEnd() g.Node

HxSwapBeforeEnd creates an hx-swap="beforeend" attribute.

func HxSwapDelete

func HxSwapDelete() g.Node

HxSwapDelete creates an hx-swap="delete" attribute.

func HxSwapInnerHTML

func HxSwapInnerHTML() g.Node

HxSwapInnerHTML creates an hx-swap="innerHTML" attribute.

func HxSwapNone

func HxSwapNone() g.Node

HxSwapNone creates an hx-swap="none" attribute.

func HxSwapOuterHTML

func HxSwapOuterHTML() g.Node

HxSwapOuterHTML creates an hx-swap="outerHTML" attribute.

func HxSync

func HxSync(selector, strategy string) g.Node

HxSync creates an hx-sync attribute for request synchronization.

Strategies:

  • drop: Drop (ignore) the request if another is in flight
  • abort: Abort the current request if a new one is triggered
  • replace: Replace the current request if a new one is triggered
  • queue: Queue requests
  • queue first: Queue requests, but execute the first immediately
  • queue last: Queue requests, but execute the last immediately
  • queue all: Queue all requests

Example:

html.Input(
    htmx.HxGet("/search"),
    htmx.HxSync("this", "replace"),
    html.Type("text"),
)

func HxTarget

func HxTarget(selector string) g.Node

HxTarget creates an hx-target attribute to specify where to swap content.

Example:

html.Button(
    htmx.HxGet("/api/data"),
    htmx.HxTarget("#results"),
    g.Text("Load"),
)

func HxTrigger

func HxTrigger(event string) g.Node

HxTrigger creates an hx-trigger attribute with a custom event.

Example:

html.Div(
    htmx.HxTrigger("click"),
    htmx.HxGet("/api/data"),
)

func HxTriggerChange

func HxTriggerChange() g.Node

HxTriggerChange creates an hx-trigger="change" attribute.

func HxTriggerClick

func HxTriggerClick() g.Node

HxTriggerClick creates an hx-trigger="click" attribute.

func HxTriggerConsume

func HxTriggerConsume(event string) g.Node

HxTriggerConsume creates an hx-trigger with consume modifier. Prevents the event from bubbling.

Example:

html.Button(
    htmx.HxTriggerConsume("click"),
    htmx.HxPost("/api/action"),
)

func HxTriggerDebounce

func HxTriggerDebounce(event, delay string) g.Node

HxTriggerDebounce creates an hx-trigger with debouncing.

Example:

html.Input(
    htmx.HxTriggerDebounce("keyup", "500ms"),
    htmx.HxGet("/search"),
)

func HxTriggerEvery

func HxTriggerEvery(duration string) g.Node

HxTriggerEvery creates an hx-trigger with polling interval.

Example:

html.Div(
    htmx.HxTriggerEvery("2s"),
    htmx.HxGet("/api/status"),
)

func HxTriggerFilter

func HxTriggerFilter(eventAndFilter string) g.Node

HxTriggerFilter creates an hx-trigger with an event filter.

Example:

html.Input(
    htmx.HxTriggerFilter("keyup[key=='Enter']"),
    htmx.HxPost("/api/submit"),
)

func HxTriggerFrom

func HxTriggerFrom(eventAndSelector string) g.Node

HxTriggerFrom creates an hx-trigger from another element.

Example:

html.Div(
    html.ID("target"),
    htmx.HxTriggerFrom("click from:#button"),
    htmx.HxGet("/api/data"),
)

func HxTriggerIntersect

func HxTriggerIntersect(options string) g.Node

HxTriggerIntersect creates an hx-trigger="intersect" attribute. Triggers when the element intersects the viewport.

Example:

html.Div(
    htmx.HxTriggerIntersect("once threshold:0.5"),
    htmx.HxGet("/api/lazy-load"),
)

func HxTriggerLoad

func HxTriggerLoad() g.Node

HxTriggerLoad creates an hx-trigger="load" attribute. Triggers when the element is first loaded.

func HxTriggerMouseEnter

func HxTriggerMouseEnter() g.Node

HxTriggerMouseEnter creates an hx-trigger="mouseenter" attribute.

func HxTriggerMouseLeave

func HxTriggerMouseLeave() g.Node

HxTriggerMouseLeave creates an hx-trigger="mouseleave" attribute.

func HxTriggerOnce

func HxTriggerOnce(event string) g.Node

HxTriggerOnce creates an hx-trigger that fires only once.

Example:

html.Div(
    htmx.HxTriggerOnce("click"),
    htmx.HxGet("/api/init"),
)

func HxTriggerQueue

func HxTriggerQueue(event, queueOption string) g.Node

HxTriggerQueue creates an hx-trigger with queue modifier.

Example:

html.Button(
    htmx.HxTriggerQueue("click", "first"),
    htmx.HxPost("/api/action"),
)

func HxTriggerRevealed

func HxTriggerRevealed() g.Node

HxTriggerRevealed creates an hx-trigger="revealed" attribute. Triggers when the element is scrolled into the viewport.

func HxTriggerSubmit

func HxTriggerSubmit() g.Node

HxTriggerSubmit creates an hx-trigger="submit" attribute.

func HxTriggerTarget

func HxTriggerTarget(event, selector string) g.Node

HxTriggerTarget creates an hx-trigger with target modifier.

Example:

html.Div(
    htmx.HxTriggerTarget("click", "#button"),
    htmx.HxGet("/api/data"),
)

func HxTriggerThrottle

func HxTriggerThrottle(event, delay string) g.Node

HxTriggerThrottle creates an hx-trigger with throttling.

Example:

html.Input(
    htmx.HxTriggerThrottle("keyup", "1s"),
    htmx.HxGet("/search"),
)

func HxValidate

func HxValidate(enabled bool) g.Node

HxValidate creates an hx-validate attribute to force validation before submit.

Example:

html.Input(
    html.Type("email"),
    html.Required(),
    htmx.HxValidate(true),
)

func HxVals

func HxVals(values map[string]any) g.Node

HxVals creates an hx-vals attribute for extra values to submit.

Example:

html.Button(
    htmx.HxPost("/api/data"),
    htmx.HxVals(map[string]any{
        "category": "urgent",
        "priority": 1,
    }),
    g.Text("Submit"),
)

func HxValsJS

func HxValsJS(jsExpr string) g.Node

HxValsJS creates an hx-vals attribute with JavaScript evaluation.

Example:

htmx.HxValsJS("js:{timestamp: Date.now()}")

func IndicatorCSS

func IndicatorCSS() g.Node

IndicatorCSS returns a style tag with default HTMX indicator styles.

Elements with class .htmx-indicator will be hidden by default and shown during HTMX requests when targeted by hx-indicator.

Example:

html.Head(
    htmx.IndicatorCSS(),
)

func IsHTMX

func IsHTMX(r *http.Request) bool

IsHTMX checks if the request is from HTMX by looking for the HX-Request header.

Example:

func handler(w http.ResponseWriter, r *http.Request) {
    if htmx.IsHTMX(r) {
        // Return partial HTML
        renderPartial(w)
    } else {
        // Return full page
        renderFullPage(w)
    }
}

func IsHTMXBoosted

func IsHTMXBoosted(r *http.Request) bool

IsHTMXBoosted checks if the request is from an element using hx-boost.

Example:

func handler(w http.ResponseWriter, r *http.Request) {
    if htmx.IsHTMXBoosted(r) {
        // Handle boosted navigation
    }
}

func Middleware

func Middleware(next http.Handler) http.Handler

Middleware creates an HTTP middleware that detects HTMX requests. It adds HTMX request information to the request context.

Example:

router := http.NewServeMux()
router.Handle("/", htmx.Middleware(handler))

func Scripts

func Scripts(version ...string) g.Node

Scripts returns a script tag that loads HTMX from CDN.

Example:

html.Head(
    htmx.Scripts(),
)

func ScriptsWithExtensions

func ScriptsWithExtensions(extensions ...string) []g.Node

ScriptsWithExtensions loads HTMX with the specified extensions.

Example:

html.Head(
    g.Group(htmx.ScriptsWithExtensions(
        htmx.ExtensionSSE,
        htmx.ExtensionWebSockets,
    )),
)

func SetHTMXLocation

func SetHTMXLocation(w http.ResponseWriter, path string)

SetHTMXLocation performs a client-side redirect without a full page reload.

Example:

htmx.SetHTMXLocation(w, "/new-page")

func SetHTMXLocationWithContext

func SetHTMXLocationWithContext(w http.ResponseWriter, context map[string]any)

SetHTMXLocationWithContext performs a client-side redirect with context.

Example:

htmx.SetHTMXLocationWithContext(w, map[string]any{
    "path": "/messages",
    "target": "#main",
    "swap": "innerHTML",
})

func SetHTMXPushURL

func SetHTMXPushURL(w http.ResponseWriter, url string)

SetHTMXPushURL pushes a new URL into the browser history stack.

Example:

htmx.SetHTMXPushURL(w, "/page/2")

func SetHTMXRedirect

func SetHTMXRedirect(w http.ResponseWriter, url string)

SetHTMXRedirect performs a client-side redirect that does a full page reload.

Example:

htmx.SetHTMXRedirect(w, "/login")

func SetHTMXRefresh

func SetHTMXRefresh(w http.ResponseWriter)

SetHTMXRefresh tells HTMX to do a full page refresh.

Example:

htmx.SetHTMXRefresh(w)

func SetHTMXReplaceURL

func SetHTMXReplaceURL(w http.ResponseWriter, url string)

SetHTMXReplaceURL replaces the current URL in the location bar.

Example:

htmx.SetHTMXReplaceURL(w, "/new-url")

func SetHTMXReselect

func SetHTMXReselect(w http.ResponseWriter, selector string)

SetHTMXReselect allows you to select a subset of the response to swap.

Example:

htmx.SetHTMXReselect(w, "#content")

func SetHTMXReswap

func SetHTMXReswap(w http.ResponseWriter, swapMethod string)

SetHTMXReswap allows you to specify how the response will be swapped.

Example:

htmx.SetHTMXReswap(w, "outerHTML")

func SetHTMXRetarget

func SetHTMXRetarget(w http.ResponseWriter, target string)

SetHTMXRetarget allows you to specify a new target for the swap.

Example:

htmx.SetHTMXRetarget(w, "#different-target")

func SetHTMXTrigger

func SetHTMXTrigger(w http.ResponseWriter, events map[string]any)

SetHTMXTrigger is a convenience function to set the HX-Trigger response header.

Example:

htmx.SetHTMXTrigger(w, map[string]any{
    "itemUpdated": map[string]int{"id": 123},
})

func SetResponseHeaders

func SetResponseHeaders(w http.ResponseWriter, headers ResponseHeaders)

SetResponseHeaders sets HTMX response headers.

Example:

htmx.SetResponseHeaders(w, htmx.ResponseHeaders{
    Trigger: map[string]any{
        "showMessage": map[string]string{"text": "Saved!"},
    },
    Refresh: false,
})

func StopPolling

func StopPolling(w http.ResponseWriter)

StopPolling sets HX-Trigger with status code 286 to stop polling.

Example:

if completed {
    htmx.StopPolling(w)
    return
}

func TriggerEvent

func TriggerEvent(w http.ResponseWriter, eventName string)

TriggerEvent sets an HX-Trigger response header with a simple event.

Example:

htmx.TriggerEvent(w, "showMessage")

func TriggerEventWithDetail

func TriggerEventWithDetail(w http.ResponseWriter, eventName string, detail map[string]any)

TriggerEventWithDetail sets an HX-Trigger response header with event details.

Example:

htmx.TriggerEventWithDetail(w, "showMessage", map[string]any{
    "level": "success",
    "message": "Item saved successfully",
})

func TriggerEvents

func TriggerEvents(w http.ResponseWriter, events map[string]any)

TriggerEvents sets multiple HX-Trigger events.

Example:

htmx.TriggerEvents(w, map[string]any{
    "event1": nil,
    "event2": map[string]string{"key": "value"},
})

Types

type ResponseHeaders

type ResponseHeaders struct {
	// Trigger allows you to trigger client-side events
	Trigger map[string]any

	// TriggerAfterSwap triggers events after the swap step
	TriggerAfterSwap map[string]any

	// TriggerAfterSettle triggers events after the settle step
	TriggerAfterSettle map[string]any

	// Redirect performs a client-side redirect
	Redirect string

	// Refresh forces a full page refresh
	Refresh bool

	// ReplaceURL replaces the current URL in the browser location bar
	ReplaceURL string

	// PushURL pushes a new URL into the browser history
	PushURL string

	// Reswap allows you to specify how the response will be swapped
	Reswap string

	// Retarget allows you to specify a new target for the swap
	Retarget string

	// Reselect allows you to select a subset of the response to swap
	Reselect string
}

ResponseHeaders contains HTMX response headers.

Jump to

Keyboard shortcuts

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