htmx

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2023 License: MIT Imports: 4 Imported by: 0

README

golangish-htmxish-logo.png

HTMX library for Go

GoDoc

This comprehensive library offers an array of functions and types specifically designed to streamline the handling of HTMX requests and the construction of responses in the Go applications.

README.md logo image courtesy of ChatGPT.

Features

  • Request and Response header helpers
  • Easy APIs to build complex HTMX responses for Locations, Reswaps, and Triggers
func myHandler(w http.ResponseWriter, r *http.Request) {
    if htmx.IsHtmx(r) {
        // do something
		
        // load up on HTMX headers and set the status code to send back to the client
        err := htmx.Response(w,
            htmx.Location("/new-location",
                htmx.Target("#my-target"),
                htmx.Swap(htmx.SwapInnerHtml.IgnoreTitle()),
                htmx.Values(map[string]string{"key": "value"}),
            ),
            htmx.StatusStopPolling,
            htmx.Trigger(
                htmx.Event("my-event"),
                htmx.Event("my-other-event", "my-other-event-value"),
                htmx.Event("my-complex-event", map[string]any{
                    "foo": "bar",
                    "baz": 123,
                }
            ),
        )
        if err != nil {
            // handle error
        }
    }
}

Installation

The minimum version of Go required is 1.18. Generics have been used to make some types and options easier to work with.

Install using go get:

go get github.com/stackus/htmx

Then import the package into your project:

import "github.com/stackus/htmx"

Working with Requests

To determine if a request is an HTMX request, use the IsHtmx function:

func MyHandler(w http.ResponseWriter, r *http.Request) {
    if htmx.IsHtmx(r) {
        // do something
    }
}

Helpers exist for each of the HTMX request headers:

  • HX-Boosted: Use the IsBoosted function to determine if the request is a boosted request
  • HX-Current-URL: Use the GetCurrentUrl function to get the current URL of the request
  • HX-History-Restore-Request: Use the IsHistoryRestoreRequest function to determine if the request is a history restore request
  • HX-Prompt: Use the GetPrompt function to get the prompt value of the request
  • HX-Request: Use the IsRequest or IsHTMX functions to determine if the request is an HTMX request
  • HX-Target: Use the GetTarget function to get the target value of the request
  • HX-Trigger-Name: Use the GetTriggerName function to get the trigger name of the request
  • HX-Trigger: Use the GetTrigger function to get the trigger value of the request

Is* functions return a boolean while Get* functions return a string. The absence of the corresponding HTMX header will return false or an empty string respectively.

Working with Responses

Use the Response function to modify the http.ResponseWriter to return an HTMX response:

func MyHandler(w http.ResponseWriter, r *http.Request) {
    err := htmx.Response(w, htmx.Retarget("/new-location"))
	if err != nil {
        // handle error
    }
}

Each of the HTMX response headers has a corresponding option to set the header:

  • HX-Location: Use the Location option with a variable number of properties to set the location header. See the Location section for more details.
  • HX-Push-Url: Use the PushURL option to push a new URL into the browser history
  • HX-Redirect: Use the Redirect option to redirect the browser to a new URL
  • HX-Refresh: Use the Refresh option to refresh the browser
  • HX-Replace-Url: Use the ReplaceUrl option to replace the current URL in the browser history
  • HX-Reswap: Use the Reswap option or one of the Swap* constants to specify how the response will be swapped. See the Reswap section for more details.
  • HX-Retarget: Use the Retarget option with a CSS selector to redirect the response to a new element
  • HX-Reselect: Use the Reselect option with a CSS selector to designate a different element in the response to be used
  • HX-Trigger: Use the Trigger option to trigger client-side events. See the Trigger section for more details.
  • HX-Trigger-After-Settle: Use the TriggerAfterSettle option to trigger client-side events after the response has settled. See the Trigger section for more details.
  • HX-Trigger-After-Swap: Use the TriggerAfterSwap option to trigger client-side events after the response has been swapped. See the Trigger section for more details.
Location

The Location option is used to set the HX-Location Response Header. It takes a path string and then an optional number of properties. The following properties are supported:

  • Source: The Source property is used to set the source element of the location header.
  • Event: The EventName property is used to set the name of the event of the location header.

    Note: This property is called EventName so that it does not conflict with the Event property used by the Trigger option.

  • Handler: The Handler property is used to set the handler of the location header.
  • Target: The Target property is used to set the target of the location header.
  • Swap: The Swap property is used to set the swap of the location header. The value may be a string or any of the Swap* constants.
  • Values: The Values property is used to set the values of the location header. The value may be anything, but it is recommended to use a map[string]any or struct with JSON tags.
  • Headers: The Headers property is used to set the headers of the location header. The value needs to be a map[string]string.
  • Select: The Select property is used to set the select of the location header.

Setting just the path:

func MyHandler(w http.ResponseWriter, r *http.Request) {
    htmx.Response(w, htmx.Location("/new-location"))
	  // Hx-Location: /new-location
}

Setting multiple properties:

func MyHandler(w http.ResponseWriter, r *http.Request) {
    htmx.Response(w, htmx.Location("/new-location",
        htmx.Target("#my-target"),
        htmx.Swap(htmx.SwapInnerHtml.IgnoreTitle()),
        htmx.Values(map[string]string{"key": "value"}),
    ))
    // Hx-Location: {"path":"/new-location","target":"#my-target","swap":"innerHTML ignoreTitle:true","values":{"key":"value"}}
}
Reswap

The Reswap option is used to set the HX-Reswap response header. Using the Reswap option directly is possible, but it is recommended to use one of the Swap* constants instead. The following constants are supported:

  • SwapInnerHtml: Sets the HX-Reswap response header to innerHTML
  • SwapOuterHtml: Sets the HX-Reswap response header to outerHTML
  • SwapBeforeBegin: Sets the HX-Reswap response header to beforebegin
  • SwapAfterBegin: Sets the HX-Reswap response header to afterbegin
  • SwapBeforeEnd: Sets the HX-Reswap response header to beforeend
  • SwapAfterEnd: Sets the HX-Reswap response header to afterend
  • SwapDelete: Sets the HX-Reswap response header to delete
  • SwapNone: Sets the HX-Reswap response header to none

The result from Reswap and each constant can be chained with modifiers to configure the header even further. The following modifiers are supported:

  • Transition: Adds transition:true to enable the use of the View Transition API
  • Swap: Used with a time.Duration to set the swap delay
  • Settle: Used with a time.Duration to set the settle delay
  • IgnoreTitle: Adds ignoreTitle:true to ignore the title of the response
  • Scroll: Used with a CSS selector to scroll to the element after swapping
  • Show: Used with a CSS selector to show the element after swapping
  • FocusScroll: Used with a boolean to set the focus scroll behavior

Setting just the reswap header two ways:

func MyHandler(w http.ResponseWriter, r *http.Request) {
    htmx.Response(w, htmx.Reswap("innerHTML"))
    // Hx-Reswap: innerHTML
    htmx.Response(w, htmx.SwapInnerHtml)
    // Hx-Reswap: innerHTML
}

Setting the reswap header with modifiers:

func MyHandler(w http.ResponseWriter, r *http.Request) {
    htmx.Response(w, htmx.SwapInnerHtml.IgnoreTitle().Transition())
    // Hx-Reswap: innerHTML ignoreTitle:true transition:true
}
Trigger

The Trigger option is used to set the HX-Trigger Response Header. It takes a variable number of events to trigger on the client.

Events are created using htmx.Event and can be either simple names or complex objects. The supported events include:

Setting a simple event:

func MyHandler(w http.ResponseWriter, r *http.Request) {
    htmx.Response(w, htmx.Trigger(htmx.Event("my-event")))
    // Hx-Trigger: {"my-event":null}
}

Setting a complex event:

func MyHandler(w http.ResponseWriter, r *http.Request) {
    myEvent := map[string]any{
        "foo": "bar",
        "baz": 123,
    }

    htmx.Response(w, htmx.Trigger(htmx.Event("my-event", myEvent)))
	  // Hx-Trigger: {"my-event":{"foo":"bar","baz":123}}
}

Setting multiple events:

func MyHandler(w http.ResponseWriter, r *http.Request) {
    htmx.Response(w, htmx.Trigger(
        htmx.Event("my-event"),
        htmx.Event("my-other-event", "my-other-event-value"),
    ))
    // Hx-Trigger: {"my-event":null,"my-other-event":"my-other-event-value"}
}

The data, which is the second parameter of the Event, is variadic. If more than one data value is passed, the event is set to an array of those values. The following events demonstrate this equivalence:

func MyHandler(w http.ResponseWriter, r *http.Request) {
    htmx.Response(w, htmx.Trigger(
        htmx.Event("my-event-1", "foo", "bar"),
        htmx.Event("my-event-2", []string{"foo", "bar"}),
    ))
    // Hx-Trigger: {"my-event-1":["foo","bar"], "my-event-2":["foo","bar"]}
}

Both TriggerAfterSettle and TriggerAfterSwap are available to trigger events after the response has settled or been swapped respectively. They take the same event arguments as Trigger.

Status

The Status option is used to set the HTTP status code of the response. There is only one status constant available:

  • StatusStopPolling: Sets the HTTP status code to 286 which is used by HTMX to halt polling requests

Setting the status code:

func MyHandler(w http.ResponseWriter, r *http.Request) {
    htmx.Response(w, htmx.StatusStopPolling)
    // HTTP/1.1 286
}

The Status option can be used to set any HTTP status code and is not limited to the constants provided by this library.

func MyHandler(w http.ResponseWriter, r *http.Request) {
    htmx.Response(w, htmx.Status(http.StatusGone))
    // HTTP/1.1 410
}

Usage with different HTTP frameworks

With the standard library, and other frameworks that adhere to its http.ResponseWriter interface, the Response function can be used directly to modify the response.

Standard Library (and some like Chi)
package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/stackus/htmx"
)

func helloWorldHandler(w http.ResponseWriter, r *http.Request) {
	// Add HTMX headers and a status code to the response
	err := htmx.Response(w,
		htmx.Location("/foo"),
		htmx.StatusStopPolling,
	)
	if err != nil {
		log.Fatal(err)
	}

	// Write the response body
	_, _ = fmt.Fprintf(w, "Hello World")
}

func main() {
	http.HandleFunc("/", helloWorldHandler)

	fmt.Println("Server starting on port 8080...")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}
Echo, Fiber, and other frameworks

For frameworks that do not use the standard library's http.ResponseWriter interface, there are request and response helpers available to make it easier to work with HTMX.

For example, with Echo:

package main

import (
	"github.com/labstack/echo/v4"

	"github.com/stackus/htmx"
	"github.com/stackus/htmx/htmxecho"
)

func main() {
	// Create a new instance of Echo
	e := echo.New()

	// Define a route for "/"
	e.GET("/", func(c echo.Context) error {
		// use echohtmx.IsHtmx to determine if the request is an HTMX request
		if echohtmx.IsHtmx(c) {
			// do something
			// Adds HTMX headers but does not set the Status Code
			r, err := echohtmx.Response(c,
				// Continue to use the base htmx types and options
				htmx.Location("/foo"),
				htmx.StatusStopPolling,
			)
			if err != nil {
				return err
			}

			// Set the HTMX status code here and response body
			return c.String(r.StatusCode(), "Hello Echo")
		}
	})

	// Start the server on port 8080
	e.Logger.Fatal(e.Start(":8080"))
}

You will find request and response helpers for the following frameworks:

The BuildResponse will return a default status of 200 if no status is set. If you need to set a status code, you can use the Status option.

Contributions

Contributions are welcome! Please open an issue or submit a pull request. If at all possible, please provide an example with your bug reports and tests with your pull requests.

Reporting Bugs
  • If you find a bug, please open an issue.
  • Include a clear description of the bug, steps to reproduce it, and any relevant logs or screenshots.
  • Before creating a new issue, please check if it has already been reported to avoid duplicates.
Suggesting Enhancements
  • We're always looking to improve our library. If you have ideas for new features or enhancements, feel free to open an issue to discuss it.
  • Clearly explain your suggestion and its potential benefits.
License

This project is licensed under the MIT License. See the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	// HxBoosted indicates that the request is a boosted request.
	//
	// See https://htmx.org/reference/#request_headers for more details.
	//
	// Use the IsBoosted() function to check this header in the request.
	HxBoosted = "Hx-Boosted"

	// HxCurrentUrl represents the current URL of the browser.
	//
	// See https://htmx.org/reference/#request_headers for more details.
	//
	// Use the GetCurrentUrl() function to fetch this header from the request.
	HxCurrentUrl = "Hx-Current-Url"

	// HxHistoryRestoreRequest is "true" if the request is for history restoration after a miss in the local history cache.
	//
	// See https://htmx.org/reference/#request_headers for more details.
	//
	// Use the IsHistoryRestoreRequest() function to check this header in the request.
	HxHistoryRestoreRequest = "Hx-History-Restore-Request"

	// HxPrompt captures the user's response to an HX-Prompt.
	//
	// See https://htmx.org/reference/#request_headers for more details.
	//
	// Use the GetPrompt() function to fetch this header from the request.
	HxPrompt = "Hx-Prompt"

	// HxRequest is always "true" if the request is an HTMX request.
	//
	// See https://htmx.org/reference/#request_headers for more details.
	//
	// Use the IsRequest() function to check this header in the request.
	HxRequest = "Hx-Request"

	// HxTarget identifies the ID of the target element, if it exists.
	//
	// See https://htmx.org/reference/#request_headers for more details.
	//
	// Use the GetTarget() function to fetch this header from the request.
	HxTarget = "Hx-Target"

	// HxTriggerName denotes the name of the triggered element, if it exists.
	//
	// See https://htmx.org/reference/#request_headers for more details.
	//
	// Use the GetTriggerName() function to fetch this header from the request.
	HxTriggerName = "Hx-Trigger-Name"
)

Request Headers

View Source
const (
	// HxLocation allows for client-side redirects without a full page reload.
	//
	// See https://htmx.org/reference/#response_headers for more details.
	//
	// Use the Location() option to set this header in the response.
	HxLocation = "Hx-Location"

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

	// HxRedirect can be used for client-side redirects that require a full page reload.
	//
	// See https://htmx.org/reference/#response_headers for more details.
	//
	// Use the Redirect() option to set this header in the response.
	HxRedirect = "Hx-Redirect"

	// HxRefresh when set to "true", triggers a full refresh of the client-side page.
	//
	// See https://htmx.org/reference/#response_headers for more details.
	//
	// Use the Refresh() option to set this header in the response.
	HxRefresh = "Hx-Refresh"

	// HxReplaceUrl replaces the current URL in the location bar.
	//
	// See https://htmx.org/reference/#response_headers for more details.
	//
	// Use the ReplaceUrl() option to set this header in the response.
	HxReplaceUrl = "Hx-Replace-Url"

	// HxReswap specifies how the response will be swapped.
	//
	// See https://htmx.org/reference/#response_headers for more details.
	//
	// Use the Reswap() option to set this header in the response.
	HxReswap = "Hx-Reswap"

	// HxRetarget updates the target of the content update to a different element on the page using a CSS selector.
	//
	// See https://htmx.org/reference/#response_headers for more details.
	//
	// Use the Retarget() option to set this header in the response.
	HxRetarget = "Hx-Retarget"

	// 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://htmx.org/reference/#response_headers for more details.
	//
	// Use the Reselect() option to set this header.
	HxReselect = "Hx-Reselect"

	// HxTriggerAfterSettle triggers client-side events after the settle step.
	//
	// See https://htmx.org/reference/#response_headers for more details.
	//
	// Use the TriggerAfterSettle() option to set this header in the response.
	HxTriggerAfterSettle = "Hx-Trigger-After-Settle"

	// HxTriggerAfterSwap triggers client-side events after the swap step.
	//
	// See https://htmx.org/reference/#response_headers for more details.
	//
	// Use the TriggerAfterSwap() option to set this header in the response.
	HxTriggerAfterSwap = "Hx-Trigger-After-Reswap"
)

Response Headers

View Source
const (
	// HxTrigger
	// (in request) the id of the trigger element if it exists
	// (in response) allows you to trigger events on the client
	//
	// More details: https://htmx.org/reference/#request_headers and https://htmx.org/reference/#response_headers
	//
	//  - Use the GetTrigger() function to fetch this header from the request
	//  - Use the Trigger(...events) option to set this header on the response
	HxTrigger = "HX-Trigger"
)

Request & Response Headers

Variables

This section is empty.

Functions

func Event

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

Event creates an event to pass to one of the Trigger options.

Simple named event:

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

Named event with string data:

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

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

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

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

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

func GetCurrentUrl

func GetCurrentUrl(r *http.Request) string

GetCurrentUrl extracts the HX-Current-URL header from an HTTP request.

It returns the current URL of the browser if the header exists. If the header is not present, it returns an empty string.

func GetPrompt

func GetPrompt(r *http.Request) string

GetPrompt extracts the HX-Prompt header from an HTTP request.

It returns the user response to an hx-prompt if the header exists. If the header is not present, it returns an empty string.

func GetTarget

func GetTarget(r *http.Request) string

GetTarget extracts the HX-Target header from an HTTP request.

It returns the ID of the target element if the header exists. If the header is not present, it returns an empty string.

func GetTrigger

func GetTrigger(r *http.Request) string

GetTrigger extracts the HX-Trigger header from an HTTP request.

It returns the ID of the trigger element if the header exists. If the header is not present, it returns an empty string.

func GetTriggerName

func GetTriggerName(r *http.Request) string

GetTriggerName extracts the HX-Trigger-Name header from an HTTP request.

It returns the name of the triggered element if the header exists. If the header is not present, it returns an empty string.

func IsBoosted

func IsBoosted(r *http.Request) bool

IsBoosted checks the HX-Boosted header

Returns true if the request is a boosted request

func IsHistoryRestoreRequest

func IsHistoryRestoreRequest(r *http.Request) bool

IsHistoryRestoreRequest determines if an HTTP request is a history restore request.

It checks the presence of the HX-History-Restore-Request header in the request. Returns true if the header is present, otherwise returns false.

func IsHtmx added in v0.1.1

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.

It checks the presence of the HX-Request header in the request. Returns true if the header is present, otherwise returns false.

func Location

func Location(path string, properties ...property) responseOptionFunc

Location sets the HX-Location header.

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

For more details, see: https://htmx.org/headers/hx-location

Simple redirection example:

htmx.Response(w, htmx.Location("/test"))
// Sets HX-Location header to "/test"

Redirection with additional target example:

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

func Refresh

func Refresh() responseOptionFunc

Refresh sets the HX-Refresh header.

When set to "true", it triggers a full refresh of the client-side page. Note: This function always sets it to "true".

Example usage:

htmx.Response(w, htmx.Refresh())
// Sets the HX-Refresh header to "true".

func Response

func Response(w http.ResponseWriter, options ...ResponseOption) error

Response modifies the http.ResponseWriter to add HTMX headers and status codes.

The following options are available:

  • Status(int) | StatusStopPolling: Sets the HTTP status code of the HTMX response.
  • Location(path, ...properties): 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 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(...events): Triggers client-side events.
  • TriggerAfterSettle(...events): Triggers client-side events after the settle step.
  • TriggerAfterSwap(...events): Triggers client-side events after the swap step.

func Swap

func Swap[T string | Reswap](swap T) propertyFunc

Swap sets the 'swap' property of the HX-Location header.

Either a string or a Reswap constant can be used.

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

func Trigger

func Trigger(events ...event) responseOptionFunc

Trigger allows you to trigger events on the client

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

Use Event to create events to pass to this option.

Simple example:

htmx.Response(w, htmx.Trigger(htmx.Event("myEvent")))
// Sets HX-Trigger header to {"myEvent":null}

Example with data:

htmx.Response(w, htmx.Trigger(htmx.Event("myEvent", "myData")))
// Sets HX-Trigger header to {"myEvent":"myData"}

Example with multiple events:

htmx.Response(w, htmx.Trigger(
	htmx.Event("myEvent", "myData"),
	htmx.Event("myOtherEvent", "myOtherData"),
))
// Sets HX-Trigger header to {"myEvent":"myData","myOtherEvent":"myOtherData"}

See also: TriggerAfterSettle and TriggerAfterSwap

func TriggerAfterSettle

func TriggerAfterSettle(events ...event) responseOptionFunc

TriggerAfterSettle triggers client-side events after the settle step.

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

For more details, see: Trigger

func TriggerAfterSwap

func TriggerAfterSwap(events ...event) responseOptionFunc

TriggerAfterSwap triggers client-side events after the swap step.

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

For more details, see: Trigger

func Values

func Values(values any) propertyFunc

Values sets the 'values' property of the HX-Location header.

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

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

Types

type EventName

type EventName string

EventName sets the 'event' property of the HX-Location header.

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

type Handler

type Handler string

Handler sets the 'handler' property of the HX-Location header.

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

type Headers

type Headers map[string]string

Headers sets the 'headers' property of the HX-Location header.

Accepts a map[string]string.

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

type HtmxResponse

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

HtmxResponse 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 BuildResponse

func BuildResponse(options ...ResponseOption) (response *HtmxResponse, err error)

BuildResponse creates a new HtmxResponse 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/htmx/echohtmx
  • Fiber: import github.com/stackus/htmx/fiberhtmx
  • Gin: import github.com/stackus/htmx/ginhtmx

func (HtmxResponse) Headers

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

func (HtmxResponse) StatusCode

func (r HtmxResponse) StatusCode() int

type PushUrl

type PushUrl string

PushUrl sets the HX-Push-Url header.

It pushes a new URL into the history stack.

Example usage:

htmx.Response(w, htmx.PushUrl("/new-url-location"))
// Sets the HX-Push-Url header to "/new-url-location".

type Redirect

type Redirect string

Redirect sets the HX-Redirect header.

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

Example usage:

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

type ReplaceUrl

type ReplaceUrl string

ReplaceUrl sets the HX-Replace-Url header.

It replaces the current URL in the location bar.

Example usage:

htmx.Response(w, htmx.ReplaceUrl("/new-url-location"))
// Sets the HX-Replace-Url header to "/new-url-location".

type Reselect

type Reselect string

Reselect sets the HX-Reselect header.

This option designates a CSS selector to determine which part of the response should be used for swapping in, effectively overriding any existing hx-select on the triggering element.

Example usage:

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

type ResponseOption added in v0.2.0

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

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

type Reswap

type Reswap string

Reswap specifies how the response will be swapped in an HTMX request.

Use the Reswap() directly to set this header in the response, or choose from the constants below for common swap styles.

The constants correspond to the different swap styles:

  • SwapInnerHtml: Replaces the inner HTML of the target element.
  • SwapOuterHtml: Replaces the entire target element with the response.
  • SwapBeforeBegin: Inserts the response before the target element.
  • SwapAfterBegin: Inserts the response before the first child of the target element.
  • SwapBeforeEnd: Inserts the response after the last child of the target element.
  • SwapAfterEnd: Inserts the response after the target element.
  • SwapDelete: Deletes the target element, regardless of the response.
  • SwapNone: Does not append content from the response (out-of-band items will still be processed).

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

Simple usage:

htmx.Response(w, htmx.Reswap("innerHTML"))
// Sets HX-Reswap header to "innerHTML"

Constant usage example (same as above):

htmx.Response(w, htmx.SwapInnerHtml)
// Also sets HX-Reswap header to "innerHTML"

Constant usage example (with modifiers):

htmx.Response(w, htmx.SwapInnerHtml.Swap(1*time.Second).Settle(2*time.Second))
// Sets HX-Reswap header to "innerHTML swap:1s settle:2s"
const (
	// SwapInnerHtml replace the inner HTML of the target element
	SwapInnerHtml Reswap = "innerHTML"
	// SwapOuterHtml replace the entire target element with the response
	SwapOuterHtml Reswap = "outerHTML"
	// SwapAfterBegin insert the response before the target element
	SwapBeforeBegin Reswap = "beforebegin"
	// SwapAfterBegin insert the response before the first child of the target element
	SwapAfterBegin Reswap = "afterbegin"
	// SwapBeforeEnd insert the response after the last child of the target element
	SwapBeforeEnd Reswap = "beforeend"
	// SwapAfterEnd insert the response after the target element
	SwapAfterEnd Reswap = "afterend"
	// SwapDelete deletes the target element regardless of the response
	SwapDelete Reswap = "delete"
	// SwapNone does not append content from response (out of band items will still be processed)
	SwapNone Reswap = "none"
)

Reswap constants

func (Reswap) FocusScroll

func (s Reswap) FocusScroll(focus bool) Reswap

FocusScroll (reswap header modifier) can be used to enable to disable scrolling to the element after swapping

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

Example usage:

htmx.Response(w, htmx.SwapInnerHtml.FocusScroll(true))
// Sets HX-Reswap header to "innerHTML focus-scroll:true"

func (Reswap) IgnoreTitle

func (s Reswap) IgnoreTitle() Reswap

IgnoreTitle (reswap header modifier) is used to ignore any <title> tags in the response

More details: https://htmx.org/attributes/hx-swap/#ignore-title

Example usage:

htmx.Response(w, htmx.SwapInnerHtml.IgnoreTitle())
// Sets HX-Reswap header to "innerHTML ignoreTitle:true"

func (Reswap) Scroll

func (s Reswap) Scroll(target string) Reswap

Scroll (reswap header modifier) is used to scroll to the "top", "bottom", a specific element after swapping

More details: https://htmx.org/attributes/hx-swap/#scrolling-scroll-show

Example usage:

htmx.Response(w, htmx.SwapInnerHtml.Scroll("top"))
// Sets HX-Reswap header to "innerHTML scroll:top"
htmx.Response(w, htmx.SwapInnerHtml.Scroll("#another-div:top"))
// Sets HX-Reswap header to "innerHTML scroll:#another-div:top"

func (Reswap) Settle

func (s Reswap) Settle(dur time.Duration) Reswap

Settle (reswap header modifier) is used to set a time to wait after swapping before triggering the settle step

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

Example usage:

htmx.Response(w, htmx.SwapInnerHtml.Settle(1*time.Second))
// Sets HX-Reswap header to "innerHTML settle:1s"

func (Reswap) Show

func (s Reswap) Show(target string) Reswap

Show (reswap header modifier) is used to show the "top", "bottom", or a specific element after swapping

More details: https://htmx.org/attributes/hx-swap/#scrolling-scroll-show

Example usage:

htmx.Response(w, htmx.SwapInnerHtml.Show("top"))
// Sets HX-Reswap header to "innerHTML show:top"
htmx.Response(w, htmx.SwapInnerHtml.Show("#another-div:top"))
// Sets HX-Reswap header to "innerHTML show:#another-div:top"

func (Reswap) Swap

func (s Reswap) Swap(dur time.Duration) Reswap

Swap (reswap header modifier) is used to set a time wait after receiving a response before swapping the content

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

Example usage:

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

func (Reswap) Transition

func (s Reswap) Transition() Reswap

Transition (reswap header modifier) allows you to specify the use of the View Transition API when a swap occurs

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

Example usage:

htmx.Response(w, htmx.SwapInnerHtml.Transition())
// Sets HX-Reswap header to "innerHTML transition:true"

type Retarget

type Retarget string

Retarget sets the HX-Retarget header.

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

Example usage:

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

type Select

type Select string

Select sets the 'select' property of the HX-Location header.

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

type Source

type Source string

Source sets the 'source' property of the HX-Location header.

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

type Status

type Status int

Status is used to set the HTTP status code of the HTMX response.

Example usage:

htmx.Response(w, htmx.Status(http.StatusGone))
// Sets the HTTP status code to 410.
const (
	// StatusStopPolling sends HTTP status code 286 to the client to stop polling.
	//
	// Example usage:
	//  htmx.Response(w, htmx.StatusStopPolling)
	//  // Sets the HTTP status code to 286.
	StatusStopPolling Status = 286
)

HTMX status codes.

type Target

type Target string

Target sets the 'target' property of the HX-Location header.

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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