htmx

package module
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2024 License: MIT Imports: 9 Imported by: 8

README

go-htmx

Seamless HTMX integration in golang applications.

GoDoc GoMod Size License Stars Go Report Card

Description

This repository contains the htmx Go package, designed to enhance server-side handling of HTML generated with the HTMX library. It provides a set of tools to easily manage swap behaviors, trigger configurations, and other HTMX-related functionalities in a Go server environment.

Features

  • Swap Configuration: Configure swap behaviors for HTMX responses, including style, timing, and scrolling.
  • Trigger Management: Define and manage triggers for HTMX events, supporting both simple and detailed triggers.
  • Middleware Support: Integrate HTMX seamlessly with Go middleware for easy HTMX header configuration.
  • io.Writer Support: The HTMX handler implements the io.Writer interface for easy integration with existing Go code.

Getting Started

Installation

To install the htmx package, use the following command:

go get -u github.com/donseba/go-htmx
Usage

initialize the htmx service like so :

package main

import (
	"log"
	"net/http"

	"github.com/donseba/go-htmx"
	"github.com/donseba/go-htmx/middleware"
)

type App struct {
	htmx *htmx.HTMX
}

func main() {
	// new app with htmx instance
	app := &App{
		htmx: htmx.New(),
	}

	mux := http.NewServeMux()
	// wrap the htmx example middleware around the http handler
	mux.Handle("/", middleware.MiddleWare(http.HandlerFunc(app.Home)))

	err := http.ListenAndServe(":3000", mux)
	log.Fatal(err)
}

func (a *App) Home(w http.ResponseWriter, r *http.Request) {
	// initiate a new htmx handler
	h := a.htmx.NewHandler(w, r)

	// check if the request is a htmx request
	if h.IsHxRequest() {
		// do something
	}
	
	// check if the request is boosted
	if h.IsHxBoosted() {
		// do something
	}
	
	// check if the request is a history restore request
	if h.IsHxHistoryRestoreRequest() { 
		// do something 
	}
	
	// check if the request is a prompt request
	if h.RenderPartial() { 
		// do something
	}
		
	// set the headers for the response, see docs for more options
	h.PushURL("http://push.url")
	h.ReTarget("#ReTarged")

	// write the output like you normally do.
	// check the inspector tool in the browser to see that the headers are set.
	_, _ = h.Write([]byte("OK"))
}
HTMX Request Checks

The htmx package provides several functions to determine the nature of HTMX requests in your Go application. These checks allow you to tailor the server's response based on specific HTMX-related conditions.

IsHxRequest

This function checks if the incoming HTTP request is made by HTMX.

func (h *Handler) IsHxRequest() bool

Usage: Use this check to identify requests initiated by HTMX and differentiate them from standard HTTP requests. Example: Applying special handling or returning partial HTML snippets in response to an HTMX request.

IsHxBoosted

Determines if the HTMX request is boosted, which typically indicates an enhancement of the user experience with HTMX's AJAX capabilities.

func (h *Handler) IsHxBoosted() bool

Usage: Useful in scenarios where you want to provide an enriched or different response for boosted requests. Example: Loading additional data or scripts that are specifically meant for AJAX-enhanced browsing.

IsHxHistoryRestoreRequest

Checks if the HTMX request is a history restore request. This type of request occurs when HTMX is restoring content from the browser's history.

func (h *Handler) IsHxHistoryRestoreRequest() bool

Usage: Helps in handling scenarios where users navigate using browser history, and the application needs to restore previous states or content. Example: Resetting certain states or re-fetching data that was previously displayed.

RenderPartial

This function returns true for HTMX requests that are either standard or boosted, as long as they are not history restore requests. It is a combined check used to determine if a partial render is appropriate.

func (h *Handler) RenderPartial() bool

Usage: Ideal for deciding when to render partial HTML content, which is a common pattern in applications using HTMX. Example: Returning only the necessary HTML fragments to update a part of the webpage, instead of rendering the entire page.

Swapping

Swapping is a way to replace the content of a dom element with the content of the response. This is done by setting the HX-Swap header to the id of the dom element you want to swap.

func (c *Controller) Route(w http.ResponseWriter, r *http.Request) {
	// initiate a new htmx handler 
	h := a.htmx.NewHandler(w, r)
	
	// Example usage of Swap 
	swap := htmx.NewSwap().Swap(time.Second * 2).ScrollBottom() 
	
	h.ReSwapWithObject(swap)
	
	_, _ = h.Write([]byte("your content"))
}
Trigger Events

Trigger events are a way to trigger events on the dom element. This is done by setting the HX-Trigger header to the event you want to trigger.

func (c *Controller) Route(w http.ResponseWriter, r *http.Request) {
	// initiate a new htmx handler 
	h := a.htmx.NewHandler(w, r)
	
	// Example usage of Swap 
	trigger := htmx.NewTrigger().AddEvent("event1").AddEventDetailed("event2", "Hello, World!") 
	
	h.TriggerWithObject(swap)
	// or 
	h.TriggerAfterSettleWithObject(swap)
	// or
	h.TriggerAfterSwapWithObject(swap)
	
	_, _ = h.Write([]byte("your content"))
}

utility methods

Notification handling

comprehensive support for triggering various types of notifications within your Go applications, enhancing user interaction and feedback. The package provides a set of functions to easily manage and trigger different notification types such as success, info, warning, error, and custom notifications. Available Notification Types

  • Success: Use for positive confirmation messages.
  • Info: Ideal for informational messages.
  • Warning: Suitable for cautionary messages.
  • Error: Use for error or failure messages.
  • Custom: Allows for defining your own notification types.
Usage

Triggering notifications is straightforward. Here are some examples demonstrating how to use each function:

func (h *Handler) MyHandlerFunc(w http.ResponseWriter, r *http.Request) {
	// Trigger a success notification 
	h.TriggerSuccess("Operation completed successfully")
	
	// Trigger an info notification 
	h.TriggerInfo("This is an informational message")

	// Trigger a warning notification 
	h.TriggerWarning("Warning: Please check your input")
	
	// Trigger an error notification 
	h.TriggerError("Error: Unable to process your request")
	
	// Trigger a custom notification 
	h.TriggerCustom("customType", "This is a custom notification", nil)
}
Notification Levels

The htmx package provides built-in support for four primary notification levels, each representing a different type of message:

  • success: Indicates successful completion of an operation.
  • info: Conveys informational messages.
  • warning: Alerts about potential issues or cautionary information.
  • error: Signals an error or problem that occurred.

Each notification type is designed to communicate specific kinds of messages clearly and effectively in your application's user interface.

Triggering Custom Notifications

In addition to these standard notification levels, the htmx package also allows for custom notifications using the TriggerCustom method. This method provides the flexibility to define a custom level and message, catering to unique notification requirements.

func (h *Handler) MyHandlerFunc(w http.ResponseWriter, r *http.Request) {
	// Trigger standard notifications 
	h.TriggerSuccess("Operation successful")
	h.TriggerInfo("This is for your information")
	h.TriggerWarning("Please be cautious")
	h.TriggerError("An error has occurred")
	
	// Trigger a custom notification 
	h.TriggerCustom("customLevel", "This is a custom notification")
}

The TriggerCustom method enables you to specify a custom level (e.g., "customLevel") and an accompanying message. This method is particularly useful when you need to go beyond the predefined notification types and implement a notification system that aligns closely with your application's specific context or branding.

Advanced Usage with Custom Variables

You can also pass additional data with your notifications. Here's an example:

func (h *Handler) MyHandlerFunc(w http.ResponseWriter, r *http.Request) {
	customData := map[string]string{"key1": "value1", "key2": "value2"}
	h.TriggerInfo("User logged in", customData)
}
the HTMX part

please refer to the htmx documentation regarding event triggering. and the example confirmation UI

HX-Trigger: {"showMessage":{"level" : "info", "message" : "Here Is A Message"}}

And handle this event like so:

document.body.addEventListener("showMessage", function(evt){
    if(evt.detail.level === "info"){
        alert(evt.detail.message);
    }
})

Each property of the JSON object on the right hand side will be copied onto the details object for the event.

Customizing Notification Event Names

In addition to the standard notification types, the htmx package allows you to customize the event name used for triggering notifications. This is done by modifying the htmx.DefaultNotificationKey. Changing this key will affect the event name in the HTMX trigger, allowing you to tailor it to specific needs or naming conventions of your application. Setting a Custom Notification Key

Before triggering notifications, you can set a custom event name as follows:

htmx.DefaultNotificationKey = "myCustomEventName"

Middleware

The htmx package is designed for versatile integration into Go applications, providing support both with and without the use of middleware. Below, we showcase two examples demonstrating the package's usage in scenarios involving middleware.

standard mux middleware example:
func MiddleWare(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()

		hxh := htmx.HxRequestHeaderFromRequest(c.Request())

		ctx = context.WithValue(ctx, htmx.ContextRequestHeader, hxh)

		next.ServeHTTP(w, r.WithContext(ctx))
	}
	return http.HandlerFunc(fn)
}
echo middleware example:
func MiddleWare(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		ctx := c.Request().Context()

		hxh := htmx.HxRequestHeaderFromRequest(c.Request())

		ctx = context.WithValue(ctx, htmx.ContextRequestHeader, hxh)

		c.SetRequest(c.Request().WithContext(ctx))

		return next(c)
	}
}

Custom logger

In case you want to use a custom logger, like zap, you can inject them into the slog package like so:

import (
    "go.uber.org/zap"
    "go.uber.org/zap/exp/zapslog"
)

func main() {
    // create a new htmx instance with the logger
    app := &App{
        htmx: htmx.New(),
    }

    zapLogger := zap.Must(zap.NewProduction())
    defer zapLogger.Sync()
    
    logger := slog.New(zapslog.NewHandler(zapLogger.Core(), nil))
    
    app.htmx.SetLog(logger)
}

Usage in other frameworks

The htmx package is designed to be versatile and can be used in various Go web frameworks. Below are examples of how to use the package in two popular Go web frameworks: Echo and Gin.

echo
func (c *controller) Hello(c echo.Context) error {
    // initiate a new htmx handler 
    h := c.app.htmx.NewHandler(c.Response(), c.Request())
    
    // Example usage of Swap 
    swap := htmx.NewSwap().Swap(time.Second * 2).ScrollBottom() 
    
    h.ReSwapWithObject(swap)
    
    _, _ = h.Write([]byte("your content"))
}
gin
func (c *controller) Hello(c *gin.Context) {
    // initiate a new htmx handler 
    h := c.app.htmx.NewHandler(c.Writer, c.Request)
    
    // Example usage of Swap 
    swap := htmx.NewSwap().Swap(time.Second * 2).ScrollBottom() 
    
    h.ReSwapWithObject(swap)
    
    _, _ = h.Write([]byte("your content"))
}

Server Sent Events (SSE)

The htmx package provides support for Server-Sent Events (SSE) in Go applications. This feature allows you to send real-time updates from the server to the client, enabling live updates and notifications in your web application.

You can read about this feature in the htmx documentation and the MDN Web Docs.

Usage

Create an endpoint in your Go application to handle SSE requests. (see the example for a better understanding)

func (a *App) SSE(w http.ResponseWriter, r *http.Request) {
    cl := &client{
        id: uuid.New().String()
        ch: make(chan *htmx.SSEMessage),
    }
    
    sseManager.Handle(w, cl)
}

In order to send a message to the client, you can use the Send method on the SSEManager object.

    go func() {
        for {
            // Send a message every seconds 
            time.Sleep(1 * time.Second) 
			
            msg := sse.
                NewMessage(fmt.Sprintf("The current time is: %v", time.Now().Format(time.RFC850))).
                WithEvent("Time")

			sseManager.Send()
		}
	}()
HTMX helper methods

There are 2 helper methods to simplify the usage of SSE in your HTMX application. The Manager is created in the background and is not exposed to the user. You can change the default worker pool size by setting the htmx.DefaultSSEWorkerPoolSize variable.


// SSEHandler handles the server-sent events. this is a shortcut and is not the preferred way to handle sse.
func (h *HTMX) SSEHandler(w http.ResponseWriter, cl sse.Client)

// SSESend sends a message to all connected clients.
func (h *HTMX) SSESend(message sse.Envelope)

Contributing

Contributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement".

Remember to give the project a star! Thanks again!

  1. Fork this repo
  2. Create a new branch with main as the base branch
  3. Add your changes
  4. Raise a Pull Request

License

Distributed under the MIT License. See LICENSE for more information.

Documentation

Overview

Package htmx offers a streamlined integration with HTMX in Go applications. It implements the standard io.Writer interface and includes middleware support, but it is not required. Allowing for the effortless incorporation of HTMX features into existing Go applications.

Index

Constants

View Source
const (
	// StatusStopPolling is the status code that will stop htmx from polling
	StatusStopPolling = 286
)

Variables

View Source
var (
	DefaultSwapDuration = time.Duration(0 * time.Millisecond)
	DefaultSettleDelay  = time.Duration(20 * time.Millisecond)

	DefaultNotificationKey   = "showMessage"
	DefaultSSEWorkerPoolSize = 5
)

Functions

func HxBoolToStr

func HxBoolToStr(b bool) string

HxBoolToStr converts a boolean value to a string.

func HxStrToBool

func HxStrToBool(str string) bool

HxStrToBool converts a string to a boolean value.

func IsHxBoosted added in v1.5.1

func IsHxBoosted(r *http.Request) bool

IsHxBoosted returns true if the request is a htmx request and the request is boosted

func IsHxHistoryRestoreRequest added in v1.5.1

func IsHxHistoryRestoreRequest(r *http.Request) bool

IsHxHistoryRestoreRequest returns true if the request is a htmx request and the request is a history restore request

func IsHxRequest added in v1.5.1

func IsHxRequest(r *http.Request) bool

IsHxRequest returns true if the request is a htmx request.

func RenderPartial added in v1.5.1

func RenderPartial(r *http.Request) bool

RenderPartial returns true if the request is an HTMX request that is either boosted or a hx request, provided it is not a history restore request.

Types

type HTMX

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

func New

func New() *HTMX

New returns a new htmx instance.

func (*HTMX) HxHeader

func (h *HTMX) HxHeader(r *http.Request) HxRequestHeader

func (*HTMX) HxResponseHeader added in v1.4.0

func (h *HTMX) HxResponseHeader(headers http.Header) *HxResponseHeader

func (*HTMX) NewHandler

func (h *HTMX) NewHandler(w http.ResponseWriter, r *http.Request) *Handler

NewHandler returns a new htmx handler.

func (*HTMX) NewSSE added in v1.7.0

func (h *HTMX) NewSSE(workerPoolSize int) error

NewSSE creates a new sse manager with the specified worker pool size.

func (*HTMX) SSEHandler added in v1.7.0

func (h *HTMX) SSEHandler(w http.ResponseWriter, r *http.Request, cl sse.Listener)

SSEHandler handles the server-sent events. this is a shortcut and is not the preferred way to handle sse.

func (*HTMX) SSESend added in v1.7.0

func (h *HTMX) SSESend(message sse.Envelope)

SSESend sends a message to all connected clients.

func (*HTMX) SetLog added in v1.6.0

func (h *HTMX) SetLog(log Logger)

SetLog sets the logger for the htmx instance.

type Handler

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

func (*Handler) Header added in v1.0.1

func (h *Handler) Header() http.Header

Header returns the header map that will be sent by WriteHeader

func (*Handler) IsHxBoosted added in v1.3.0

func (h *Handler) IsHxBoosted() bool

IsHxBoosted returns true if the request is a htmx request and the request is boosted

func (*Handler) IsHxHistoryRestoreRequest added in v1.3.0

func (h *Handler) IsHxHistoryRestoreRequest() bool

IsHxHistoryRestoreRequest returns true if the request is a htmx request and the request is a history restore request

func (*Handler) IsHxRequest added in v1.3.0

func (h *Handler) IsHxRequest() bool

IsHxRequest returns true if the request is a htmx request.

func (*Handler) JustWrite added in v1.6.0

func (h *Handler) JustWrite(data []byte)

JustWrite writes the data to the connection as part of an HTTP reply.

func (*Handler) JustWriteHTML added in v1.6.0

func (h *Handler) JustWriteHTML(html template.HTML)

JustWriteHTML is a helper that writes HTML data to the connection.

func (*Handler) JustWriteJSON added in v1.6.0

func (h *Handler) JustWriteJSON(data any)

JustWriteJSON is a helper that writes json data to the connection.

func (*Handler) JustWriteString added in v1.6.0

func (h *Handler) JustWriteString(s string)

JustWriteString is a helper that writes string data to the connection.

func (*Handler) Location

func (h *Handler) Location(li *LocationInput) error

Location can be used to trigger a client side redirection without reloading the whole page https://htmx.org/headers/hx-location/

func (*Handler) MustWrite added in v1.6.0

func (h *Handler) MustWrite(data []byte)

MustWrite writes the data to the connection as part of an HTTP reply.

func (*Handler) MustWriteHTML added in v1.6.0

func (h *Handler) MustWriteHTML(html template.HTML)

MustWriteHTML is a helper that writes HTML data to the connection.

func (*Handler) MustWriteJSON added in v1.6.0

func (h *Handler) MustWriteJSON(data any)

MustWriteJSON is a helper that writes json data to the connection.

func (*Handler) MustWriteString added in v1.6.0

func (h *Handler) MustWriteString(s string)

MustWriteString is a helper that writes string data to the connection.

func (*Handler) PushURL

func (h *Handler) PushURL(val string)

PushURL pushes a new url into the history stack. https://htmx.org/headers/hx-push-url/

func (*Handler) ReSelect added in v1.1.0

func (h *Handler) ReSelect(val string)

ReSelect a CSS selector that allows you to choose which part of the response is used to be swapped in. Overrides an existing hx-select on the triggering element

func (*Handler) ReSwap

func (h *Handler) ReSwap(val string)

ReSwap allows you to specify how the response will be swapped. See hx-swap for possible values https://htmx.org/attributes/hx-swap/

func (*Handler) ReSwapWithObject added in v1.3.0

func (h *Handler) ReSwapWithObject(s *Swap)

ReSwapWithObject allows you to specify how the response will be swapped. See hx-swap for possible values https://htmx.org/attributes/hx-swap/

func (*Handler) ReTarget

func (h *Handler) ReTarget(val string)

ReTarget a CSS selector that updates the target of the content update to a different element on the page

func (*Handler) Redirect

func (h *Handler) Redirect(val string)

Redirect can be used to do a client-side redirect to a new location

func (*Handler) Refresh

func (h *Handler) Refresh(val bool)

Refresh if set to true the client side will do a full refresh of the page

func (*Handler) RenderPartial added in v1.3.0

func (h *Handler) RenderPartial() bool

RenderPartial returns true if the request is an HTMX request that is either boosted or a standard request, provided it is not a history restore request.

func (*Handler) ReplaceURL

func (h *Handler) ReplaceURL(val string)

ReplaceURL allows you to replace the current URL in the browser location history. https://htmx.org/headers/hx-replace-url/

func (*Handler) Request added in v1.0.1

func (h *Handler) Request() HxRequestHeader

Request returns the HxHeaders from the request

func (*Handler) ResponseHeader added in v1.4.0

func (h *Handler) ResponseHeader(header HxResponseKey) string

ResponseHeader returns the value of the response header

func (*Handler) StopPolling added in v1.1.0

func (h *Handler) StopPolling()

StopPolling sets the response status to 286, which will stop htmx from polling

func (*Handler) Trigger

func (h *Handler) Trigger(val string)

Trigger triggers events as soon as the response is received. https://htmx.org/headers/hx-trigger/

func (*Handler) TriggerAfterSettle

func (h *Handler) TriggerAfterSettle(val string)

TriggerAfterSettle trigger events after the settling step. https://htmx.org/headers/hx-trigger/

func (*Handler) TriggerAfterSettleWithObject added in v1.3.0

func (h *Handler) TriggerAfterSettleWithObject(t *Trigger)

TriggerAfterSettleWithObject trigger events after the settling step. https://htmx.org/headers/hx-trigger/

func (*Handler) TriggerAfterSwap

func (h *Handler) TriggerAfterSwap(val string)

TriggerAfterSwap trigger events after the swap step. https://htmx.org/headers/hx-trigger/

func (*Handler) TriggerAfterSwapWithObject added in v1.3.0

func (h *Handler) TriggerAfterSwapWithObject(t *Trigger)

TriggerAfterSwapWithObject trigger events after the swap step. https://htmx.org/headers/hx-trigger/

func (*Handler) TriggerCustom added in v1.5.0

func (h *Handler) TriggerCustom(custom, message string, vars ...map[string]any)

func (*Handler) TriggerError added in v1.5.0

func (h *Handler) TriggerError(message string, vars ...map[string]any)

func (*Handler) TriggerInfo added in v1.5.0

func (h *Handler) TriggerInfo(message string, vars ...map[string]any)

func (*Handler) TriggerSuccess added in v1.5.0

func (h *Handler) TriggerSuccess(message string, vars ...map[string]any)

func (*Handler) TriggerWarning added in v1.5.0

func (h *Handler) TriggerWarning(message string, vars ...map[string]any)

func (*Handler) TriggerWithObject added in v1.3.0

func (h *Handler) TriggerWithObject(t *Trigger)

TriggerWithObject triggers events as soon as the response is received. https://htmx.org/headers/hx-trigger/

func (*Handler) Write

func (h *Handler) Write(data []byte) (n int, err error)

Write writes the data to the connection as part of an HTTP reply.

func (*Handler) WriteHTML added in v1.5.1

func (h *Handler) WriteHTML(html template.HTML) (n int, err error)

WriteHTML is a helper that writes HTML data to the connection.

func (*Handler) WriteHeader added in v1.0.1

func (h *Handler) WriteHeader(code int)

WriteHeader sets the HTTP response header with the provided status code.

func (*Handler) WriteJSON added in v1.5.1

func (h *Handler) WriteJSON(data any) (n int, err error)

WriteJSON is a helper that writes json data to the connection.

func (*Handler) WriteString added in v1.5.1

func (h *Handler) WriteString(s string) (n int, err error)

WriteString is a helper that writes string data to the connection.

type HxRequestHeader

type HxRequestHeader struct {
	HxBoosted               bool
	HxCurrentURL            string
	HxHistoryRestoreRequest bool
	HxPrompt                string
	HxRequest               bool
	HxTarget                string
	HxTriggerName           string
	HxTrigger               string
}

func HxRequestHeaderFromRequest added in v1.4.0

func HxRequestHeaderFromRequest(r *http.Request) HxRequestHeader

type HxRequestHeaderKey added in v1.5.1

type HxRequestHeaderKey string
const (
	// ContextRequestHeader is the context key for the htmx request header.
	ContextRequestHeader = "htmx-request-header"

	HxRequestHeaderBoosted               HxRequestHeaderKey = "HX-Boosted"
	HxRequestHeaderCurrentURL            HxRequestHeaderKey = "HX-Current-URL"
	HxRequestHeaderHistoryRestoreRequest HxRequestHeaderKey = "HX-History-Restore-Request"
	HxRequestHeaderPrompt                HxRequestHeaderKey = "HX-Prompt"
	HxRequestHeaderRequest               HxRequestHeaderKey = "HX-Request"
	HxRequestHeaderTarget                HxRequestHeaderKey = "HX-Target"
	HxRequestHeaderTriggerName           HxRequestHeaderKey = "HX-Trigger-Name"
	HxRequestHeaderTrigger               HxRequestHeaderKey = "HX-Trigger"
)

func (HxRequestHeaderKey) String added in v1.5.1

func (x HxRequestHeaderKey) String() string

type HxResponseHeader

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

func (*HxResponseHeader) Get added in v1.4.0

func (*HxResponseHeader) Set

func (h *HxResponseHeader) Set(k HxResponseKey, val string)

type HxResponseKey

type HxResponseKey string
var (
	HXLocation           HxResponseKey = "HX-Location"             // Allows you to do a client-side redirect that does not do a full page reload
	HXPushUrl            HxResponseKey = "HX-Push-Url"             // pushes a new url into the history stack
	HXRedirect           HxResponseKey = "HX-Redirect"             // can be used to do a client-side redirect to a new location
	HXRefresh            HxResponseKey = "HX-Refresh"              // if set to "true" the client side will do a full refresh of the page
	HXReplaceUrl         HxResponseKey = "HX-Replace-Url"          // replaces the current URL in the location bar
	HXReswap             HxResponseKey = "HX-Reswap"               // Allows you to specify how the response will be swapped. See hx-swap for possible values
	HXRetarget           HxResponseKey = "HX-Retarget"             // A CSS selector that updates the target of the content update to a different element on the page
	HXReselect           HxResponseKey = "HX-Reselect"             // A CSS selector that allows you to choose which part of the response is used to be swapped in. Overrides an existing hx-select on the triggering element
	HXTrigger            HxResponseKey = "HX-Trigger"              // allows you to trigger client side events, see the documentation for more info
	HXTriggerAfterSettle HxResponseKey = "HX-Trigger-After-Settle" // allows you to trigger client side events, see the documentation for more info
	HXTriggerAfterSwap   HxResponseKey = "HX-Trigger-After-Swap"   // allows you to trigger client side events, see the documentation for more info
)

func (HxResponseKey) String

func (h HxResponseKey) String() string

type LocationInput

type LocationInput struct {
	Source  string                 `json:"source"`  // source - the source element of the request
	Event   string                 `json:"event"`   //event - an event that "triggered" the request
	Handler string                 `json:"handler"` //handler - a callback that will handle the response HTML
	Target  string                 `json:"target"`  //target - the target to swap the response into
	Swap    string                 `json:"swap"`    //swap - how the response will be swapped in relative to the target
	Values  map[string]interface{} `json:"values"`  //values - values to submit with the request
	Header  map[string]interface{} `json:"headers"` //headers - headers to submit with the request

}

type Logger added in v1.6.0

type Logger interface {
	Warn(msg string, args ...any)
}

type Swap added in v1.3.0

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

func NewSwap added in v1.3.0

func NewSwap() *Swap

NewSwap returns a new Swap

func (*Swap) FocusScroll added in v1.3.0

func (s *Swap) FocusScroll(focusScroll bool) *Swap

FocusScroll enables or disables the focus scroll behaviour

func (*Swap) IgnoreTitle added in v1.3.0

func (s *Swap) IgnoreTitle(ignoreTitle bool) *Swap

IgnoreTitle enables or disables the Title

func (*Swap) Scroll added in v1.3.0

func (s *Swap) Scroll(direction SwapDirection, target ...string) *Swap

Scroll sets the scrolling behavior to scroll to the top or bottom

func (*Swap) ScrollBottom added in v1.3.0

func (s *Swap) ScrollBottom(target ...string) *Swap

ScrollBottom sets the scrolling behavior to scroll to the bottom of the target element

func (*Swap) ScrollTop added in v1.3.0

func (s *Swap) ScrollTop(target ...string) *Swap

ScrollTop sets the scrolling behavior to scroll to the top of the target element

func (*Swap) Settle added in v1.3.0

func (s *Swap) Settle(swap ...time.Duration) *Swap

Settle modifies the amount of time that htmx will wait after receiving a response to settle the content

func (*Swap) Show added in v1.3.0

func (s *Swap) Show(direction SwapDirection, target ...string) *Swap

Show sets the scrolling behavior to scroll to the top or bottom

func (*Swap) ShowBottom added in v1.3.0

func (s *Swap) ShowBottom(target ...string) *Swap

ShowBottom sets the scrolling behavior to scroll to the bottom of the target element

func (*Swap) ShowTop added in v1.3.0

func (s *Swap) ShowTop(target ...string) *Swap

ShowTop sets the scrolling behavior to scroll to the top of the target element

func (*Swap) String added in v1.3.0

func (s *Swap) String() string

String returns the string representation of the Swap

func (*Swap) Style added in v1.3.0

func (s *Swap) Style(style SwapStyle) *Swap

Style sets the style of the swap, default is innerHTML and can be changed in htmx.config.defaultSwapStyle

func (*Swap) Swap added in v1.3.0

func (s *Swap) Swap(swap ...time.Duration) *Swap

Swap modifies the amount of time that htmx will wait after receiving a response to swap the content

func (*Swap) Transition added in v1.3.0

func (s *Swap) Transition(transition bool) *Swap

Transition enables or disables the transition see : https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API

type SwapDirection added in v1.3.0

type SwapDirection string

SwapDirection modifies the scrolling behavior of the target element

const (
	SwapDirectionTop    SwapDirection = "top"
	SwapDirectionBottom SwapDirection = "bottom"
)

func (SwapDirection) String added in v1.3.0

func (s SwapDirection) String() string

type SwapScrolling added in v1.3.0

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

func (*SwapScrolling) String added in v1.3.0

func (s *SwapScrolling) String() string

type SwapScrollingMode added in v1.3.0

type SwapScrollingMode string
const (
	// ScrollingScroll You can also change the scrolling behavior of the target element by using the scroll and show modifiers, both of which take the values top and bottom
	ScrollingScroll SwapScrollingMode = "scroll"

	// ScrollingShow You can also change the scrolling behavior of the target element by using the scroll and show modifiers, both of which take the values top and bottom
	ScrollingShow SwapScrollingMode = "show"
)

func (SwapScrollingMode) String added in v1.3.0

func (s SwapScrollingMode) String() string

type SwapStyle added in v1.3.0

type SwapStyle string
const (
	// SwapInnerHTML replaces the inner html of the target element
	SwapInnerHTML SwapStyle = "innerHTML"

	// SwapOuterHTML replaces the entire target element with the response
	SwapOuterHTML SwapStyle = "outerHTML"

	// SwapBeforeBegin insert the response before the target element
	SwapBeforeBegin SwapStyle = "beforebegin"

	// SwapAfterBegin insert the response before the first child of the target element
	SwapAfterBegin SwapStyle = "afterbegin"

	// SwapBeforeEnd insert the response after the last child of the target element
	SwapBeforeEnd SwapStyle = "beforeend"

	// SwapAfterEnd insert the response after the target element
	SwapAfterEnd SwapStyle = "afterend"

	// SwapDelete deletes the target element regardless of the response
	SwapDelete SwapStyle = "delete"

	// SwapNone does not append content from response (out of band items will still be processed).
	SwapNone SwapStyle = "none"
)

func (SwapStyle) String added in v1.3.0

func (s SwapStyle) String() string

type SwapTiming added in v1.3.0

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

func (*SwapTiming) String added in v1.3.0

func (s *SwapTiming) String() string

type SwapTimingMode added in v1.3.0

type SwapTimingMode string

SwapTimingMode modifies the amount of time that htmx will wait after receiving a response to swap or settle the content

const (
	// TimingSwap You can modify the amount of time that htmx will wait after receiving a response to swap the content by including a swap modifier
	TimingSwap SwapTimingMode = "swap"

	// TimingSettle you can modify the time between the swap and the settle logic by including a settle modifier:
	TimingSettle SwapTimingMode = "settle"
)

func (SwapTimingMode) String added in v1.3.0

func (s SwapTimingMode) String() string

type Trigger added in v1.3.0

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

func NewTrigger added in v1.3.0

func NewTrigger() *Trigger

NewTrigger returns a new Trigger set

func (*Trigger) AddError added in v1.8.0

func (t *Trigger) AddError(message string, vars ...map[string]any)

func (*Trigger) AddEvent added in v1.3.0

func (t *Trigger) AddEvent(event string) *Trigger

func (*Trigger) AddEventDetailed added in v1.3.0

func (t *Trigger) AddEventDetailed(event, message string) *Trigger

AddEventDetailed adds a trigger to the Trigger set

func (*Trigger) AddEventObject added in v1.3.0

func (t *Trigger) AddEventObject(event string, details map[string]any) *Trigger

AddEventObject adds a trigger to the Trigger set

func (*Trigger) AddInfo added in v1.8.0

func (t *Trigger) AddInfo(message string, vars ...map[string]any)

func (*Trigger) AddSuccess added in v1.8.0

func (t *Trigger) AddSuccess(message string, vars ...map[string]any)

func (*Trigger) AddWarning added in v1.8.0

func (t *Trigger) AddWarning(message string, vars ...map[string]any)

func (*Trigger) String added in v1.3.0

func (t *Trigger) String() string

String returns the string representation of the Trigger set

Directories

Path Synopsis
examples
sse

Jump to

Keyboard shortcuts

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