htmx

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 6 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 templ components:

<button { htmx.HxGet("/api/users")... } { htmx.HxTarget("#user-list")... } { htmx.HxSwap("innerHTML")... }>
    Load Users
</button>

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:

<button { htmx.HxGet("/content")... } { htmx.HxTarget("#container")... } { htmx.HxSwap("beforeend")... }>
    Load
</button>

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:

<input { htmx.HxGet("/search")... } { htmx.HxTriggerDebounce("keyup", "500ms")... } { htmx.HxTarget("#results")... }/>

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!",
    },
})

Progressive Enhancement

Use hx-boost for seamless navigation:

<div { htmx.HxBoost(true)... }>
    <a href="/page1">Page 1</a>
    <a href="/page2">Page 2</a>
</div>

Loading States

Show indicators during requests:

<button { htmx.HxPost("/api/submit")... } { htmx.HxIndicator("#spinner")... } { htmx.HxDisabledElt("this")... }>
    Submit
</button>
<div id="spinner" class="htmx-indicator">Loading...</div>

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() templ.Component

CloakCSS returns a templ.Component with CSS to prevent flash of unstyled content for elements with hx-cloak attribute.

Example (in .templ files):

@htmx.CloakCSS()

func ConfigMeta

func ConfigMeta(config map[string]string) templ.Component

ConfigMeta returns a templ.Component that renders meta tags for HTMX configuration.

Example (in .templ files):

@htmx.ConfigMeta(map[string]string{"defaultSwapStyle": "outerHTML"})

func ExtensionScript

func ExtensionScript(extension string) templ.Component

ExtensionScript returns a templ.Component for a specific HTMX extension script tag.

Example (in .templ files):

@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) templ.Attributes

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

Example (in .templ files):

<div { htmx.HxBoost(true)... }>

func HxCloak

func HxCloak() templ.Attributes

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

Example (in .templ files):

<div { htmx.HxCloak()... } { htmx.HxGet("/content")... }>

func HxConfirm

func HxConfirm(message string) templ.Attributes

HxConfirm creates an hx-confirm attribute for confirmation dialogs.

Example (in .templ files):

<button { htmx.HxDelete("/api/item/123")... } { htmx.HxConfirm("Are you sure?")... }>Delete</button>

func HxDelete

func HxDelete(url string) templ.Attributes

HxDelete creates an hx-delete attribute for DELETE requests.

Example (in .templ files):

<button { htmx.HxDelete("/api/delete/123")... } { htmx.HxConfirm("Are you sure?")... }>Delete</button>

func HxDisabledElt

func HxDisabledElt(selector string) templ.Attributes

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

Example (in .templ files):

<button { htmx.HxPost("/api/submit")... } { htmx.HxDisabledElt("this")... }>Submit</button>

func HxDisinherit

func HxDisinherit(attributes string) templ.Attributes

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

Example (in .templ files):

<div { htmx.HxDisinherit("hx-select hx-get")... }>

func HxEncoding

func HxEncoding(encoding string) templ.Attributes

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

Example (in .templ files):

<form { htmx.HxPost("/api/upload")... } { htmx.HxEncoding("multipart/form-data")... }>

func HxExt

func HxExt(extension string) templ.Attributes

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

Example (in .templ files):

<div { htmx.HxExt("json-enc")... } { htmx.HxPost("/api/data")... }>

func HxGet

func HxGet(url string) templ.Attributes

HxGet creates an hx-get attribute for GET requests.

Example (in .templ files):

<button { htmx.HxGet("/api/data")... }>Load Data</button>

func HxHeaders

func HxHeaders(headers map[string]string) templ.Attributes

HxHeaders creates an hx-headers attribute for custom headers.

Example (in .templ files):

<button { htmx.HxPost("/api/data")... } { htmx.HxHeaders(map[string]string{"X-API-Key": "secret"})... }>

func HxHistory

func HxHistory(enabled bool) templ.Attributes

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

Example (in .templ files):

<div { htmx.HxHistory(false)... } { htmx.HxBoost(true)... }>

func HxInclude

func HxInclude(selector string) templ.Attributes

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

Example (in .templ files):

<button { htmx.HxPost("/api/submit")... } { htmx.HxInclude("#extra-data")... }>Submit</button>

func HxIndicator

func HxIndicator(selector string) templ.Attributes

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

Example (in .templ files):

<button { htmx.HxGet("/api/slow")... } { htmx.HxIndicator("#spinner")... }>Load</button>

func HxParams

func HxParams(params string) templ.Attributes

HxParams creates an hx-params attribute to filter parameters.

Values: "*" (all), "none", "param1,param2" (include), "not param1,param2" (exclude)

Example (in .templ files):

<form { htmx.HxPost("/api/submit")... } { htmx.HxParams("email,name")... }>

func HxPatch

func HxPatch(url string) templ.Attributes

HxPatch creates an hx-patch attribute for PATCH requests.

Example (in .templ files):

<button { htmx.HxPatch("/api/partial-update/123")... }>Patch</button>

func HxPost

func HxPost(url string) templ.Attributes

HxPost creates an hx-post attribute for POST requests.

Example (in .templ files):

<form { htmx.HxPost("/api/submit")... }>

func HxPreserve

func HxPreserve(enabled bool) templ.Attributes

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

Example (in .templ files):

<video { htmx.HxPreserve(true)... } src="/video.mp4"></video>

func HxPrompt

func HxPrompt(message string) templ.Attributes

HxPrompt creates an hx-prompt attribute for user input.

Example (in .templ files):

<button { htmx.HxPost("/api/comment")... } { htmx.HxPrompt("Enter your comment")... }>Add</button>

func HxPushURL

func HxPushURL(enabled bool) templ.Attributes

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

Example (in .templ files):

<button { htmx.HxGet("/page/2")... } { htmx.HxPushURL(true)... }>Next Page</button>

func HxPushURLWithPath

func HxPushURLWithPath(path string) templ.Attributes

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

Example (in .templ files):

<button { htmx.HxGet("/api/page/2")... } { htmx.HxPushURLWithPath("/page/2")... }>Next</button>

func HxPut

func HxPut(url string) templ.Attributes

HxPut creates an hx-put attribute for PUT requests.

Example (in .templ files):

<button { htmx.HxPut("/api/update/123")... }>Update</button>

func HxReplaceURL

func HxReplaceURL(enabled bool) templ.Attributes

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

Example (in .templ files):

<button { htmx.HxGet("/search?q=test")... } { htmx.HxReplaceURL(true)... }>Search</button>

func HxReplaceURLWithPath

func HxReplaceURLWithPath(path string) templ.Attributes

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

func HxSelect

func HxSelect(selector string) templ.Attributes

HxSelect creates an hx-select attribute for response filtering.

Example (in .templ files):

<button { htmx.HxGet("/full-page")... } { htmx.HxSelect("#content")... }>Load Content</button>

func HxSelectOOB

func HxSelectOOB(selector string) templ.Attributes

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

Example:

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

func HxSwap

func HxSwap(strategy string) templ.Attributes

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

Strategies: innerHTML, outerHTML, beforebegin, afterbegin, beforeend, afterend, delete, none

Example (in .templ files):

<button { htmx.HxGet("/api/item")... } { htmx.HxSwap("outerHTML")... }>Replace</button>

func HxSwapAfterBegin

func HxSwapAfterBegin() templ.Attributes

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

func HxSwapAfterEnd

func HxSwapAfterEnd() templ.Attributes

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

func HxSwapBeforeBegin

func HxSwapBeforeBegin() templ.Attributes

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

func HxSwapBeforeEnd

func HxSwapBeforeEnd() templ.Attributes

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

func HxSwapDelete

func HxSwapDelete() templ.Attributes

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

func HxSwapInnerHTML

func HxSwapInnerHTML() templ.Attributes

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

func HxSwapNone

func HxSwapNone() templ.Attributes

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

func HxSwapOuterHTML

func HxSwapOuterHTML() templ.Attributes

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

func HxSync

func HxSync(selector, strategy string) templ.Attributes

HxSync creates an hx-sync attribute for request synchronization.

Strategies: drop, abort, replace, queue, queue first, queue last, queue all

Example (in .templ files):

<input { htmx.HxGet("/search")... } { htmx.HxSync("this", "replace")... } type="text"/>

func HxTarget

func HxTarget(selector string) templ.Attributes

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

Example (in .templ files):

<button { htmx.HxGet("/api/data")... } { htmx.HxTarget("#results")... }>Load</button>

func HxTrigger

func HxTrigger(event string) templ.Attributes

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

Example (in .templ files):

<div { htmx.HxTrigger("click")... } { htmx.HxGet("/api/data")... }>

func HxTriggerChange

func HxTriggerChange() templ.Attributes

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

func HxTriggerClick

func HxTriggerClick() templ.Attributes

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

func HxTriggerConsume

func HxTriggerConsume(event string) templ.Attributes

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

Example (in .templ files):

<button { htmx.HxTriggerConsume("click")... } { htmx.HxPost("/api/action")... }>

func HxTriggerDebounce

func HxTriggerDebounce(event, delay string) templ.Attributes

HxTriggerDebounce creates an hx-trigger with debouncing.

Example (in .templ files):

<input { htmx.HxTriggerDebounce("keyup", "500ms")... } { htmx.HxGet("/search")... }/>

func HxTriggerEvery

func HxTriggerEvery(duration string) templ.Attributes

HxTriggerEvery creates an hx-trigger with polling interval.

Example (in .templ files):

<div { htmx.HxTriggerEvery("2s")... } { htmx.HxGet("/api/status")... }>

func HxTriggerFilter

func HxTriggerFilter(eventAndFilter string) templ.Attributes

HxTriggerFilter creates an hx-trigger with an event filter.

Example (in .templ files):

<input { htmx.HxTriggerFilter("keyup[key=='Enter']")... } { htmx.HxPost("/api/submit")... }/>

func HxTriggerFrom

func HxTriggerFrom(eventAndSelector string) templ.Attributes

HxTriggerFrom creates an hx-trigger from another element.

Example (in .templ files):

<div id="target" { htmx.HxTriggerFrom("click from:#button")... } { htmx.HxGet("/api/data")... }>

func HxTriggerIntersect

func HxTriggerIntersect(options string) templ.Attributes

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

Example (in .templ files):

<div { htmx.HxTriggerIntersect("once threshold:0.5")... } { htmx.HxGet("/api/lazy-load")... }>

func HxTriggerLoad

func HxTriggerLoad() templ.Attributes

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

func HxTriggerMouseEnter

func HxTriggerMouseEnter() templ.Attributes

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

func HxTriggerMouseLeave

func HxTriggerMouseLeave() templ.Attributes

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

func HxTriggerOnce

func HxTriggerOnce(event string) templ.Attributes

HxTriggerOnce creates an hx-trigger that fires only once.

Example (in .templ files):

<div { htmx.HxTriggerOnce("click")... } { htmx.HxGet("/api/init")... }>

func HxTriggerQueue

func HxTriggerQueue(event, queueOption string) templ.Attributes

HxTriggerQueue creates an hx-trigger with queue modifier.

Example (in .templ files):

<button { htmx.HxTriggerQueue("click", "first")... } { htmx.HxPost("/api/action")... }>

func HxTriggerRevealed

func HxTriggerRevealed() templ.Attributes

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

func HxTriggerSubmit

func HxTriggerSubmit() templ.Attributes

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

func HxTriggerTarget

func HxTriggerTarget(event, selector string) templ.Attributes

HxTriggerTarget creates an hx-trigger with target modifier.

Example (in .templ files):

<div { htmx.HxTriggerTarget("click", "#button")... } { htmx.HxGet("/api/data")... }>

func HxTriggerThrottle

func HxTriggerThrottle(event, delay string) templ.Attributes

HxTriggerThrottle creates an hx-trigger with throttling.

Example (in .templ files):

<input { htmx.HxTriggerThrottle("keyup", "1s")... } { htmx.HxGet("/search")... }/>

func HxValidate

func HxValidate(enabled bool) templ.Attributes

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

Example (in .templ files):

<input type="email" required { htmx.HxValidate(true)... }/>

func HxVals

func HxVals(values map[string]any) templ.Attributes

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

Example (in .templ files):

<button { htmx.HxPost("/api/data")... } { htmx.HxVals(map[string]any{"category": "urgent"})... }>

func HxValsJS

func HxValsJS(jsExpr string) templ.Attributes

HxValsJS creates an hx-vals attribute with JavaScript evaluation.

Example:

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

func IndicatorCSS

func IndicatorCSS() templ.Component

IndicatorCSS returns a templ.Component with default HTMX indicator styles.

Example (in .templ files):

@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) templ.Component

Scripts returns a templ.Component that renders the HTMX script tag from CDN.

Example (in .templ files):

@htmx.Scripts()

func ScriptsWithExtensions

func ScriptsWithExtensions(extensions ...string) templ.Component

ScriptsWithExtensions returns a templ.Component that loads HTMX with the specified extensions.

Example (in .templ files):

@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