ghtmx

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

README

ghtmx

codecov

A compiled Go template engine where htmx is a first-class, compile-checked language concept — a hard fork of templ (see TEMPL_SYNTAX_BASELINE.md and NOTICE) that adds route-aware bindings, compile-time fragments, and a server-driven event contract, with a stdlib-only runtime.

  • hx-post={ handlers.CreateUser } resolves against your actual Go routes at build time; renaming a route breaks the build at every binding site.
  • fragment blocks compile to byte-identical inline and standalone entry points for htmx partial updates.
  • event declarations generate the only symbols that can emit HX-Trigger, with typed payloads.

Documentation: ghtmx.dev is the published site, built from docs/official/ — itself a ghtmx application, serving these documents and every example, compiled natively or to wasm. The sources it renders are SYNTAX.md (the language), DIAGNOSTICS.md (every diagnostic), CONFIG.md (settings and flags), AUTH.md (sessions and CSRF), MIGRATION.md (upgrading), and the site-only pages under docs/official/pages/ (the landing page, getting started, build targets, htmx versions). The Go API reference is on pkg.go.dev.

Install

Two supported paths, verified on Linux, macOS, and Windows by internal/installcheck on every CI run:

With the Go toolchain:

go install github.com/go-monolith/ghtmx/cmd/ghtmx@latest
go install golang.org/x/tools/gopls@latest   # embedded-Go support in the LSP

From a release archive: download the archive for your platform from the GitHub release, verify it against checksums.txt, and put the binary on your PATH:

sha256sum --check --ignore-missing checksums.txt    # macOS: shasum -a 256 --check
tar -xzf ghtmx_<version>_linux_amd64.tar.gz ghtmx   # .zip on Windows (verify with Get-FileHash)

On Linux, macOS, and WSL, scripts/install.sh does those steps for you and installs gopls alongside when a Go toolchain is present:

curl -fsSL https://raw.githubusercontent.com/go-monolith/ghtmx/main/scripts/install.sh | bash

It reads GHTMX_VERSION (default: the latest release) and GHTMX_BIN_DIR (default: $GOBIN, then $GOPATH/bin, then ~/.local/bin), verifies the checksum before installing anything, and tells you what to add to your PATH — it never edits startup files. It is a convenience wrapper around the release archive, not a third path; native Windows uses the manual steps above.

VS Code users: that same line is the whole setup. When it finds the code CLI and the ghtmx extension is not installed yet, it asks whether to add it, and installs the .vsix from the same release if you say yes:

Install the ghtmx VS Code extension (syntax highlighting, diagnostics, completion)? [y/N]

It only ever asks — answering anything but y installs nothing, and a run with no terminal to ask on (a pipeline, CI) skips the question. Pass --no-interactive to turn every prompt off, GHTMX_INSTALL_VSCODE=1 to say yes in advance, or GHTMX_SKIP_VSCODE=1 to never be asked:

curl -fsSL https://raw.githubusercontent.com/go-monolith/ghtmx/main/scripts/install.sh | bash -s -- --no-interactive

Both paths yield the same single-version binary: ghtmx version prints the release tag.

Supported htmx versions

A project pins one htmx version, and every hx-* attribute — names, values, combinations — is checked against that version's surface. The pin also decides which script ghtmxgen.HTMXScript() serves, so the markup the compiler checked and the htmx the browser runs cannot disagree.

Pin Family Notes
2.0.0 – 2.0.10 htmx 2 2.0.10 is the default; 2.0.5 added the inherit keyword
4.0.0 htmx 4 explicit inheritance, hx-status, hx-query, morph swaps

Without a ghtmx.json a project is on 2.0.10 — htmx 2. Opting into htmx 4 is one key:

{
  "htmxVersion": "4.0.0"
}

or ghtmx generate -htmx-version 4.0.0 for a single invocation. htmx 1.x is unsupported, 3.x never existed, and prereleases are rejected: a bad pin is GHTMX-E0502, and a construct outside the pinned surface is GHTMX-E0501.

Moving an existing project between the two is mechanical and documented, diagnostic by diagnostic: ghtmx.dev/docs/htmx-versions.

Editor support

The VS Code, Neovim, and JetBrains extensions are attached to the GitHub releases alongside the binaries, from v0.1.5 onward. They are thin clients: highlighting is local, and diagnostics, completion, hover, and go to definition all come from ghtmx lsp, so behavior is the same in all three. Each needs ghtmx and gopls already on your PATH — installing an extension does not install them; scripts/install.sh above does. It installs the VS Code extension as well, so the table below is the route for the other two editors and for picking a specific version by hand.

Editor Release asset Install
VS Code ghtmx-vscode-<ext>.vsix code --install-extension ghtmx-vscode-<ext>.vsix
JetBrains ghtmx-jetbrains-<ext>.zip Settings → Plugins → ⚙ → Install Plugin from Disk
Neovim ghtmx-nvim-<ext>.tar.gz Extract onto your runtimepath

<ext> is the extension version, which is not the release tag: an extension versioned X.Y.* works with any module vX.Y.*, so a 0.1.0 extension is the right one to take off the v0.1.5 release. editors/README.md has the compatibility table and the per-editor setup, including the LSP4IJ requirement on JetBrains community editions.

The CLI beyond generate

Two flags are easy to miss and belong in a consumer's Makefile or CI alongside ghtmx generate -check:

  • ghtmx routes prints the discovered route table, and ghtmx routes -json emits it machine-readably — verb, path, handler, origin, recognizer, and source position — so scripts and tests can assert what the toolchain believes your application serves, instead of recomputing it.

  • ghtmx fmt -fail writes nothing and exits non-zero if any template would change: the CI form of ghtmx fmt.

  • ghtmx routes -check-against routes.json compares that table against the routes your own router reports, and fails on any disagreement. The routetable package is the same thing for a Go test — Load reads the table, Normalize brings your framework's path syntax into line, and Diff reports what the two disagree about:

    declared, err := routetable.Load(".")
    actual := routetable.Normalize(fromMyRouter(), routetable.ColonStyle)
    if report := routetable.Report(routetable.Diff(declared, actual)); report != "" {
        t.Errorf("route table and router disagree:\n%s", report)
    }
    

    This matters most once you take the //ghtmx:route escape hatch: generate -check verifies template-versus-generated-code drift, but only this verifies that the paths ghtmx believes in are the paths your framework actually serves.

CONFIG.md documents both, along with the dev-mode environment variables that let a running application hot-reload template text without recompiling.

Test coverage

Every CI run publishes its profile to Codecov, which is where the badge above, the line-by-line report, and each pull request's coverage diff come from. Codecov reports; it does not gate, and its line-coverage figure is not the statement-coverage number the gate below measures.

The gate is the coverage CI job, which holds statement coverage of the project's own code at 90% or above and fails the build below that floor. The threshold is a compile-time constant in internal/covergate, so lowering it is a reviewed diff rather than a workflow edit.

"Own code" is what this project writes and is answerable for. Both the gate and the Codecov report exclude:

Excluded Why
*_ghtmx.go Generated by the compiler; gated by internal/corpusgate and the conformance suite instead
internal/lsp/** Ported from the Go Language Server project (see NOTICE)
internal/safehtml/** Adapted from google/safehtml (see NOTICE)
examples/** Documentation; compiled and vetted by internal/corpusgate
**/fixture/**, **/testprogram/** Test input, not code under test

CONTRIBUTING.md has the command that reproduces the gate locally and why its flags are what they are.

Coverage in consuming projects

The same reasoning applies to a project built on ghtmx: committed *_ghtmx.go files are verified by compile, vet, and this repository's conformance suite — not by your line coverage. Linters that honour the // Code generated by ghtmx - DO NOT EDIT. header (golangci-lint does) already skip them, but Go's own -cover does not, so a coverage gate will count generated statements against you unless you exclude them the way this repository does.

For Codecov, ignore the generated suffix in codecov.yml:

ignore:
  - "*_ghtmx.go"
  - "**/*_ghtmx.go"

For a threshold checked from the profile itself, strip generated files before measuring (the suffix is your generatedSuffix setting, _ghtmx.go by default):

go test -coverprofile=cover.out ./...
grep -v '_ghtmx.go:' cover.out > cover.own.out
go tool cover -func=cover.own.out

Stability (pre-1.0)

ghtmx is pre-1.0: breaking changes to language syntax, generated-code shape, and the runtime API may land between minor versions. Every breaking change carries a CHANGELOG.md entry with a migration note — that discipline is enforced by a build gate. Pin a version and read the changelog before upgrading.

MIGRATION.md is the upgrade index: what breaks between releases, the htmx 2 → 4 path, and where each version's migration notes live.

License

Apache-2.0. Portions derived from templ (MIT) — see NOTICE.

Documentation

Overview

Package ghtmx is the runtime for ghtmx templates: the API that generated code calls, and the helpers an application calls around it.

ghtmx is a fork of templ that makes htmx a first-class part of the template language. A .ghtmx file declares components as templ does, and adds two constructs of its own — fragment blocks, which compile to byte-identical inline and standalone entry points for htmx partial updates, and event declarations, which generate the only symbols that can emit HX-Trigger, with typed payloads. Route bindings such as hx-post={ handlers.CreateItem } are checked against the handlers the project actually registers.

Templates are compiled ahead of time by the ghtmx command, which also provides the language server the editor integrations talk to:

go install github.com/go-monolith/ghtmx/cmd/ghtmx@latest
ghtmx generate

Most of this package is called by generated code rather than by hand. What an application uses directly is the Component interface, the http.Handler wrapper Handler and its options, the HX-* response helpers (SetRetarget, SetPushURL, SetRedirect, and the rest), IsHTMXRequest for branching on the request, and HTMXScriptTag to serve a pinned, integrity-checked htmx build.

Documentation

The full documentation — the language, every diagnostic, the configuration reference, and a getting-started walkthrough — is at https://ghtmx.dev. The source lives in the repository and the site renders it, so the two cannot drift.

Stability

Pre-1.0: breaking changes to the language syntax, the shape of generated code, and this API are allowed between minor versions, and each one is recorded in CHANGELOG.md with a migration note.

Index

Constants

View Source
const DefaultCSRFHeaderName = "X-CSRF-Token"

DefaultCSRFHeaderName is the request header CSRFHeader uses unless the application names another one.

View Source
const FailedSanitizationURL = SafeURL("about:invalid#TemplFailedSanitizationURL")

FailedSanitizationURL is returned if a URL fails sanitization checks.

Variables

View Source
var NopComponent = ComponentFunc(func(ctx context.Context, w io.Writer) error { return nil })

NopComponent is a component that doesn't render anything.

Functions

func Bool

func Bool(value bool) bool

Bool attribute value.

func CSRFHeader

func CSRFHeader(token string, headerName ...string) string

CSRFHeader returns an hx-headers attribute value attaching the application's CSRF token to every request the element issues (FR-092):

<form hx-post={ handlers.CreateUser } hx-headers={ ghtmx.CSRFHeader(token) }>

The same attribute works for all state-changing verbs (hx-post, hx-put, hx-patch, hx-delete). Placed on a common ancestor it reaches every element below it — implicitly under htmx 2.0.x, and only as hx-headers:inherited={ ghtmx.CSRFHeader(token) } under htmx 4, whose attribute inheritance is explicit (a bare hx-headers on a wrapper is reported as GHTMX-W0202 there). The token is supplied by the application — the engine neither generates nor validates tokens — and the value is JSON, escaped like any attribute value when rendered, so no hand-written header plumbing is involved.

Pass headerName to use a header other than X-CSRF-Token; only the first name is used. The name must be a valid HTTP header token and the token value Latin-1-safe (real CSRF tokens are ASCII): the browser rejects anything else when htmx calls setRequestHeader at request time.

Token generation and request verification live in the auth package (secure cookie session middleware): its session middleware derives the per-session token handlers read with auth.CSRFTokenFrom, and its CSRF middleware verifies this header on unsafe methods.

func CSSID

func CSSID(name string, css string) string

CSSID calculates an ID.

func ClearChildren

func ClearChildren(ctx context.Context) context.Context

func EscapePathSegment

func EscapePathSegment(s string) string

EscapePathSegment percent-encodes a value for use as a single URL path segment. Generated route constructors call it for every path parameter (S1.1): the escaping context is fixed by the engine and is not selectable at the binding site.

func EscapePathWildcard

func EscapePathWildcard(s string) string

EscapePathWildcard percent-encodes a rest-of-path value ({name...} parameters): each segment is escaped individually and separators are preserved.

func EscapeQueryValue

func EscapeQueryValue(s string) string

EscapeQueryValue percent-encodes a value for use in a URL query component.

func EscapeString

func EscapeString[T ~string](s T) string

EscapeString escapes HTML text within templates.

func GetBuffer

func GetBuffer() *bytes.Buffer

func GetNonce

func GetNonce(ctx context.Context) (nonce string)

GetNonce returns the CSP nonce value set with WithNonce, or an empty string if none has been set.

func HTMXScriptIntegrity added in v0.1.9

func HTMXScriptIntegrity(version string) (string, bool)

HTMXScriptIntegrity returns the pinned subresource-integrity hash for version, and whether the version has one. It lets a project that serves htmx itself (WithScriptSrc) assert in a test that the vendored file is the exact published build the tag pins, without scraping rendered HTML.

func InitializeContext

func InitializeContext(ctx context.Context) context.Context

InitializeContext initializes context used to store internal state used during rendering.

func IsHTMXRequest

func IsHTMXRequest(r *http.Request) bool

IsHTMXRequest reports whether the request was issued by htmx (the HX-Request header). Adapters use it for automatic render-mode selection (FR-035); handler code can branch on it explicitly.

func IsHistoryRestoreRequest added in v0.2.0

func IsHistoryRestoreRequest(r *http.Request) bool

IsHistoryRestoreRequest reports whether the request is htmx refetching a page for back/forward navigation (the HX-History-Restore-Request header, sent alongside HX-Request). Such a request wants the full page: htmx 4 selects the [hx-history-elt] element out of the response and swaps it over the current one, and htmx 2 does the same when the element is present. A bare fragment has no such element, so htmx 4 would swap in nothing. Adapters' automatic render-mode selection treats it as a full-page request for that reason.

func JSONString

func JSONString(v any) (string, error)

JSONString returns a JSON encoded string of v.

func JoinStringErrs

func JoinStringErrs[T stringable](s T, errs ...error) (string, error)

JoinStringErrs joins an optional list of errors.

func ReleaseBuffer

func ReleaseBuffer(b *bytes.Buffer)

func RenderAttributes

func RenderAttributes(ctx context.Context, w io.Writer, attributes Attributer) (err error)

func RenderCSSItems

func RenderCSSItems(ctx context.Context, w io.Writer, classes ...any) (err error)

RenderCSSItems renders the CSS to the writer, if the items haven't already been rendered.

func RenderScriptItems

func RenderScriptItems(ctx context.Context, w io.Writer, scripts ...ComponentScript) (err error)

RenderScriptItems renders a <script> element, if the script has not already been rendered.

func ResolveAttributeValue

func ResolveAttributeValue[T attributeValue](v T, errs ...error) (string, error)

ResolveAttributeValue converts an attribute expression value to an HTML-escaped string suitable for use in an attribute value. It handles ComponentScript values by returning their Call field (already escaped), and falls back to HTML-escaping fmt.Sprint for other types.

func SafeScript

func SafeScript(functionName string, params ...any) string

SafeScript encodes unknown parameters for safety for inside HTML attributes.

func SafeScriptInline

func SafeScriptInline(functionName string, params ...any) string

SafeScript encodes unknown parameters for safety for inline scripts.

func SetLocation

func SetLocation(w http.ResponseWriter, path string)

SetLocation sets HX-Location in its simple string form: htmx navigates to path with an ajax request, swapping into the body without a full page load. htmx also accepts a JSON object form (path plus target, swap, and other context fields), which this helper does not cover — a path starting with "{" would be parsed as that JSON form by htmx.

func SetPushURL

func SetPushURL(w http.ResponseWriter, url string)

SetPushURL sets HX-Push-Url: pushes url into the browser history. SetPushURLDisabled prevents a push the request would otherwise perform.

func SetPushURLDisabled

func SetPushURLDisabled(w http.ResponseWriter)

SetPushURLDisabled sets HX-Push-Url: false.

func SetRedirect

func SetRedirect(w http.ResponseWriter, url string)

SetRedirect sets HX-Redirect: htmx performs a full page load of url.

func SetRefresh

func SetRefresh(w http.ResponseWriter)

SetRefresh sets HX-Refresh: htmx performs a full page refresh.

func SetReplaceURL

func SetReplaceURL(w http.ResponseWriter, url string)

SetReplaceURL sets HX-Replace-Url: replaces the current history entry. SetReplaceURLDisabled prevents a replacement.

func SetReplaceURLDisabled

func SetReplaceURLDisabled(w http.ResponseWriter)

SetReplaceURLDisabled sets HX-Replace-Url: false.

func SetReselect

func SetReselect(w http.ResponseWriter, selector string)

SetReselect sets HX-Reselect: a CSS selector choosing the part of the response to swap in, overriding hx-select.

func SetReswap

func SetReswap(w http.ResponseWriter, style SwapStyle, modifiers ...SwapModifier)

SetReswap sets HX-Reswap: the swap style (and modifiers) overriding hx-swap for this response.

func SetRetarget

func SetRetarget(w http.ResponseWriter, selector string)

SetRetarget sets HX-Retarget: a CSS selector overriding the swap target for this response.

func SupportedHtmxVersions

func SupportedHtmxVersions() []string

SupportedHtmxVersions returns the htmx versions the script helper can emit, in numeric version order.

func ToGoHTML

func ToGoHTML(ctx context.Context, c Component) (s template.HTML, err error)

ToGoHTML renders the component to a Go html/template template.HTML string.

func Version

func Version() string

func WithChildren

func WithChildren(ctx context.Context, children Component) context.Context

func WithContentType

func WithContentType(contentType string) func(*ComponentHandler)

WithContentType sets the Content-Type header returned by the ComponentHandler.

func WithErrorHandler

func WithErrorHandler(eh func(r *http.Request, err error) http.Handler) func(*ComponentHandler)

WithErrorHandler sets the error handler used if rendering fails.

func WithNonce

func WithNonce(ctx context.Context, nonce string) context.Context

WithNonce sets a CSP nonce on the context and returns it.

func WithStatus

func WithStatus(status int) func(*ComponentHandler)

WithStatus sets the HTTP status code returned by the ComponentHandler.

func WithStreaming

func WithStreaming() func(*ComponentHandler)

WithStreaming sets the ComponentHandler to stream the response instead of buffering it.

Types

type Attributer

type Attributer interface {
	Items() []KeyValue[string, any]
}

type Attributes

type Attributes map[string]any

Attributes is an alias to map[string]any made for spread attributes.

func (Attributes) Items

func (a Attributes) Items() []KeyValue[string, any]

Returns the items of the attributes map in key sorted order.

type CSSClass

type CSSClass interface {
	ClassName() string
}

CSSClass provides a class name.

func Class deprecated

func Class(name string) CSSClass

Class returns a CSS class name.

Deprecated: use a string instead.

func SafeClass deprecated

func SafeClass(name string) CSSClass

SafeClass bypasses CSS class name validation.

Deprecated: use a string instead.

type CSSClasses

type CSSClasses []any

CSSClasses is a slice of CSS classes.

func Classes

func Classes(classes ...any) CSSClasses

Classes for CSS. Supported types are string, ConstantCSSClass, ComponentCSSClass, map[string]bool.

func (CSSClasses) String

func (classes CSSClasses) String() string

String returns the names of all CSS classes.

type CSSHandler

type CSSHandler struct {
	Logger  func(err error)
	Classes []ComponentCSSClass
}

CSSHandler is a HTTP handler that serves CSS.

func NewCSSHandler

func NewCSSHandler(classes ...CSSClass) CSSHandler

NewCSSHandler creates a handler that serves a stylesheet containing the CSS of the classes passed in. This is used by the CSSMiddleware to provide global stylesheets for templ components.

func (CSSHandler) ServeHTTP

func (cssh CSSHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type CSSMiddleware

type CSSMiddleware struct {
	Path       string
	CSSHandler CSSHandler
	Next       http.Handler
}

CSSMiddleware renders a global stylesheet.

func NewCSSMiddleware

func NewCSSMiddleware(next http.Handler, classes ...CSSClass) CSSMiddleware

NewCSSMiddleware creates HTTP middleware that renders a global stylesheet of ComponentCSSClass CSS if the request path matches, or updates the HTTP context to ensure that any handlers that use ghtmx.Components skip rendering <style> elements for classes that are included in the global stylesheet. By default, the stylesheet path is /styles/ghtmx.css

func (CSSMiddleware) ServeHTTP

func (cssm CSSMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Component

type Component interface {
	// Render the template.
	Render(ctx context.Context, w io.Writer) error
}

Component is the interface that all templates implement.

func FromGoHTML

func FromGoHTML(t *template.Template, data any) Component

FromGoHTML creates a templ Component from a Go html/template template.

func GetChildren

func GetChildren(ctx context.Context) Component

GetChildren from the context.

func HTMXScriptTag

func HTMXScriptTag(version string, opts ...ScriptOption) Component

HTMXScriptTag returns a component rendering the script tag for the given htmx version, with its subresource-integrity hash (FR-091). Rendering fails for a version outside the supported surface set — use the generated ghtmxgen.HTMXScript(), which bakes the configured version so tag and configuration cannot diverge.

func Join

func Join(components ...Component) Component

Join returns a single `ghtmx.Component` that will render provided components in order. If any of the components return an error the Join component will immediately return with the error.

func Raw

func Raw[T ~string](html T, errs ...error) Component

Raw renders the input HTML to the output without applying HTML escaping.

Use of this component presents a security risk - the HTML should come from a trusted source, because it will be included as-is in the output.

type ComponentCSSClass

type ComponentCSSClass struct {
	// ID of the class, will be autogenerated.
	ID string
	// Definition of the CSS.
	Class SafeCSS
}

ComponentCSSClass is a ghtmx.CSS

func (ComponentCSSClass) ClassName

func (css ComponentCSSClass) ClassName() string

ClassName of the CSS class.

type ComponentFunc

type ComponentFunc func(ctx context.Context, w io.Writer) error

ComponentFunc converts a function that matches the Component interface's Render method into a Component.

func (ComponentFunc) Render

func (cf ComponentFunc) Render(ctx context.Context, w io.Writer) error

Render the template.

type ComponentHandler

type ComponentHandler struct {
	Component      Component
	Status         int
	ContentType    string
	ErrorHandler   func(r *http.Request, err error) http.Handler
	StreamResponse bool
}

ComponentHandler is a http.Handler that renders components.

func Handler

func Handler(c Component, options ...func(*ComponentHandler)) *ComponentHandler

Handler creates a http.Handler that renders the template.

func (ComponentHandler) ServeHTTP

func (ch ComponentHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface.

func (*ComponentHandler) ServeHTTPBuffered

func (ch *ComponentHandler) ServeHTTPBuffered(w http.ResponseWriter, r *http.Request)

func (*ComponentHandler) ServeHTTPStreamed

func (ch *ComponentHandler) ServeHTTPStreamed(w http.ResponseWriter, r *http.Request)

type ComponentScript

type ComponentScript struct {
	// Name of the script, e.g. print.
	Name string
	// Function to render.
	Function string
	// Call of the function in JavaScript syntax, including parameters, and
	// ensures parameters are HTML escaped; useful for injecting into HTML
	// attributes like onclick, onhover, etc.
	//
	// Given:
	//    functionName("some string",12345)
	// It would render:
	//    __ghtmx_functionName_sha(&#34;some string&#34;,12345))
	//
	// This is can be injected into HTML attributes:
	//    <button onClick="__ghtmx_functionName_sha(&#34;some string&#34;,12345))">Click Me</button>
	Call string
	// Call of the function in JavaScript syntax, including parameters. It
	// does not HTML escape parameters; useful for directly calling in script
	// elements.
	//
	// Given:
	//    functionName("some string",12345)
	// It would render:
	//    __ghtmx_functionName_sha("some string",12345))
	//
	// This is can be used to call the function inside a script tag:
	//    <script>__ghtmx_functionName_sha("some string",12345))</script>
	CallInline string
}

ComponentScript is a templ Script template.

func JSFuncCall

func JSFuncCall[T ~string](functionName T, args ...any) ComponentScript

JSFuncCall calls a JavaScript function with the given arguments.

It can be used in event handlers, e.g. onclick, onhover, etc. or directly in HTML.

func JSUnsafeFuncCall

func JSUnsafeFuncCall[T ~string](js T) ComponentScript

JSUnsafeFuncCall calls arbitrary JavaScript in the js parameter.

Use of this function presents a security risk - the JavaScript must come from a trusted source, because it will be included as-is in the output.

func (ComponentScript) Render

func (c ComponentScript) Render(ctx context.Context, w io.Writer) error

type ConstantCSSClass deprecated

type ConstantCSSClass string

ConstantCSSClass is a string constant of a CSS class name.

Deprecated: use a string instead.

func (ConstantCSSClass) ClassName

func (css ConstantCSSClass) ClassName() string

ClassName of the CSS class.

type Error

type Error struct {
	Err error
	// FileName of the template file.
	FileName string
	// Line index of the error.
	Line int
	// Col index of the error.
	Col int
}

Error returned during template rendering.

func (Error) Error

func (e Error) Error() string

func (Error) Unwrap

func (e Error) Unwrap() error

type FlushComponent

type FlushComponent struct {
}

func Flush

func Flush() FlushComponent

Flush flushes the output buffer after all its child components have been rendered.

func (FlushComponent) Render

func (f FlushComponent) Render(ctx context.Context, w io.Writer) (err error)

type Fragment

type Fragment interface {
	// Component supplies Render, so a Fragment composes anywhere a
	// component can. On a standalone wrapper there is no page around the
	// fragment: Render writes exactly the bytes RenderFragment writes.
	Component
	// RenderFragment renders only the fragment's markup, with no
	// surrounding page chrome, and writes no HTTP status code or headers.
	RenderFragment(ctx context.Context, w io.Writer) error
}

Fragment is a component with a standalone render mode (FR-031). The compiler emits one Fragment-returning entry point per declared fragment: Render and RenderFragment both execute only the fragment's body — a standalone wrapper carries no page around it — so the two methods are byte-identical on generated fragments. RenderFragment exists as the intention-revealing name for htmx swap handlers (FR-034) and as the adapter integration point for automatic mode selection (FR-035).

Both methods work directly against any io.Writer, including an http.ResponseWriter inside a plain net/http handler with no adapter imported (FR-034, FR-090). On this explicit path the engine only ever calls Write: it sets no HTTP status code, no response headers, and does not flush, so the handler keeps full control of the response. Render errors return to the caller unswallowed; the engine adds no recover or panic of its own.

type JSExpression

type JSExpression string

JSExpression represents a JavaScript expression intended for use as an argument for script templates. The string value of JSExpression will be inserted directly as JavaScript code in function call arguments.

type JSONScriptElement

type JSONScriptElement struct {
	// ID of the element in the DOM.
	ID string
	// Type of the script element, defaults to "application/json".
	Type string
	// Data that will be encoded as JSON.
	Data any
	// Nonce is a function that returns a CSP nonce.
	// Defaults to CSPNonceFromContext.
	// See https://content-security-policy.com/nonce for more information.
	Nonce func(ctx context.Context) string
}

func JSONScript

func JSONScript(id string, data any) JSONScriptElement

JSONScript renders a JSON object inside a script element. e.g. <script type="application/json">{"foo":"bar"}</script>

func (JSONScriptElement) Render

func (j JSONScriptElement) Render(ctx context.Context, w io.Writer) (err error)

func (JSONScriptElement) WithNonceFrom

func (j JSONScriptElement) WithNonceFrom(f func(context.Context) string) JSONScriptElement

WithNonceFrom sets the value of the nonce attribute of the script element to the value returned by the given function.

func (JSONScriptElement) WithNonceFromString

func (j JSONScriptElement) WithNonceFromString(nonce string) JSONScriptElement

WithNonceFromString sets the value of the nonce attribute of the script element to the given string.

func (JSONScriptElement) WithType

WithType sets the value of the type attribute of the script element.

type KeyValue

type KeyValue[TKey comparable, TValue any] struct {
	Key   TKey   `json:"name"`
	Value TValue `json:"value"`
}

KeyValue is a key and value pair.

func KV

func KV[TKey comparable, TValue any](key TKey, value TValue) KeyValue[TKey, TValue]

KV creates a new key/value pair from the input key and value.

type OnceHandle

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

OnceHandle is used to ensure that the children of its `Once` method are are only rendered once per context.

func NewOnceHandle

func NewOnceHandle(opts ...OnceOpt) *OnceHandle

NewOnceHandle creates a OnceHandle used to ensure that the children of its `Once` method are only rendered once per context.

func (*OnceHandle) Once

func (o *OnceHandle) Once() Component

Once returns a component that renders its children once per context.

type OnceOpt

type OnceOpt func(*OnceHandle)

func WithComponent

func WithComponent(c Component) OnceOpt

WithOnceComponent sets the component to be rendered once per context. This can be used instead of setting the children of the `Once` method, for example, if creating a code component outside of a templ HTML template.

type OrderedAttributes

type OrderedAttributes []KeyValue[string, any]

OrderedAttributes stores attributes in order of insertion.

func (OrderedAttributes) Items

func (a OrderedAttributes) Items() []KeyValue[string, any]

type SafeCSS

type SafeCSS string

SafeCSS is CSS that has been sanitized.

func SanitizeCSS

func SanitizeCSS[T ~string](property string, value T) SafeCSS

SanitizeCSS sanitizes CSS properties to ensure that they are safe.

type SafeCSSProperty

type SafeCSSProperty string

type SafeURL

type SafeURL string

SafeURL is a URL that has been sanitized.

func JoinURLErrs

func JoinURLErrs[T ~string](s T, errs ...error) (SafeURL, error)

JoinURLErrs joins an optional list of errors and returns a sanitized SafeURL.

func URL

func URL(s string) SafeURL

URL sanitizes the input string s and returns a SafeURL.

type ScriptOption

type ScriptOption func(*scriptConfig)

ScriptOption configures HTMXScriptTag.

func WithScriptSrc

func WithScriptSrc(url string) ScriptOption

WithScriptSrc serves htmx from the given URL (self-hosted or another CDN) instead of jsDelivr. The integrity attribute still pins the configured version's official asset, so a self-hosted file must be that exact published build.

type SwapModifier

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

SwapModifier is one hx-swap modifier, constructed only through the Swap* modifier functions below.

func SwapDelay

func SwapDelay(d time.Duration) SwapModifier

SwapDelay delays the swap after the response is received. Durations are truncated to whole milliseconds; negative values clamp to zero.

func SwapEmpty added in v0.1.23

func SwapEmpty(enabled bool) SwapModifier

SwapEmpty controls whether the main swap still runs when the response holds only out-of-band content (htmx 4).

func SwapFocusScroll

func SwapFocusScroll(enabled bool) SwapModifier

SwapFocusScroll overrides focus preservation scrolling for the swap, in the htmx 2 spelling (focus-scroll:). htmx 4 renamed the modifier: use SwapFocusScrollV4 there.

func SwapFocusScrollV4 added in v0.1.23

func SwapFocusScrollV4(enabled bool) SwapModifier

SwapFocusScrollV4 is SwapFocusScroll in the htmx 4 spelling (focusScroll:); htmx 2 does not recognise it.

func SwapIgnoreTitle

func SwapIgnoreTitle() SwapModifier

SwapIgnoreTitle keeps the page title unchanged even when the response contains a <title> element.

func SwapScroll

func SwapScroll(spec string) SwapModifier

SwapScroll scrolls the target after the swap: "top" or "bottom", optionally prefixed with a selector ("#list:bottom"). The spec must not contain whitespace — hx-swap specs are space-separated, so htmx itself cannot express such selectors; whitespace here yields a zero modifier. htmx 4 dropped the selector prefix: pair SwapScroll("bottom") with SwapScrollTarget instead.

func SwapScrollTarget added in v0.1.23

func SwapScrollTarget(selector string) SwapModifier

SwapScrollTarget names the element SwapScroll scrolls (htmx 4). The selector must not contain whitespace (see SwapScroll).

func SwapSettle

func SwapSettle(d time.Duration) SwapModifier

SwapSettle delays the settle step after the swap. Durations are truncated to whole milliseconds; negative values clamp to zero.

func SwapShow

func SwapShow(spec string) SwapModifier

SwapShow scrolls the viewport to show the target after the swap: "top" or "bottom", optionally prefixed with a selector. The spec must not contain whitespace (see SwapScroll). htmx 4 dropped the selector prefix: pair SwapShow("top") with SwapShowTarget instead.

func SwapShowTarget added in v0.1.23

func SwapShowTarget(selector string) SwapModifier

SwapShowTarget names the element SwapShow brings into view (htmx 4). The selector must not contain whitespace (see SwapScroll).

func SwapStrip added in v0.1.23

func SwapStrip(enabled bool) SwapModifier

SwapStrip controls whether the response's outer wrapper element is removed before swapping (htmx 4).

func SwapTarget added in v0.1.23

func SwapTarget(selector string) SwapModifier

SwapTarget retargets the swap from within the swap spec (htmx 4). The selector must not contain whitespace (see SwapScroll).

func SwapTransition

func SwapTransition() SwapModifier

SwapTransition requests a view transition for the swap.

type SwapStyle

type SwapStyle string

SwapStyle is an hx-swap swap style of the pinned htmx surface. Using the typed constants keeps invalid styles out of HX-Reswap at compile time; the set is asserted against the embedded surface data in tests.

const (
	SwapInnerHTML   SwapStyle = "innerHTML"
	SwapOuterHTML   SwapStyle = "outerHTML"
	SwapTextContent SwapStyle = "textContent"
	SwapBeforeBegin SwapStyle = "beforebegin"
	SwapAfterBegin  SwapStyle = "afterbegin"
	SwapBeforeEnd   SwapStyle = "beforeend"
	SwapAfterEnd    SwapStyle = "afterend"
	SwapDelete      SwapStyle = "delete"
	SwapNone        SwapStyle = "none"

	// htmx 4 styles; htmx 2 does not recognise them.
	SwapInnerMorph SwapStyle = "innerMorph"
	SwapOuterMorph SwapStyle = "outerMorph"
	SwapOuterSync  SwapStyle = "outerSync"
	// htmx 4 aliases of the four insertion positions.
	SwapBefore  SwapStyle = "before"
	SwapPrepend SwapStyle = "prepend"
	SwapAppend  SwapStyle = "append"
	SwapAfter   SwapStyle = "after"
)

Directories

Path Synopsis
adapters
nethttp
Package nethttp adapts ghtmx rendering to net/http handlers with opt-in automatic render-mode selection (FR-035).
Package nethttp adapts ghtmx rendering to net/http handlers with opt-in automatic render-mode selection (FR-035).
chi module
echo module
fiber module
fiberv3 module
gin module
Package auth provides secure cookie session authentication for server-rendered ghtmx applications: cookie hygiene, opaque session tokens, CSRF protection, and htmx-aware login redirects, behind one small interface the application implements.
Package auth provides secure cookie session authentication for server-rendered ghtmx applications: cookie hygiene, opaque session tokens, CSRF protection, and htmx-aware login redirects, behind one small interface the application implements.
benchmarks
corpus
Package corpus is the DATA-007 benchmark corpus: named page, fragment, and route-binding rendering workloads.
Package corpus is the DATA-007 benchmark corpus: named page, fragment, and route-binding rendering workloads.
This package is inspired by the GOEXPERIMENT approach of allowing feature flags for experimenting with breaking changes.
This package is inspired by the GOEXPERIMENT approach of allowing feature flags for experimenting with breaking changes.
cmd
ghtmx command
ghtmx/lspcmd/pls
Code generated for gopls supervision (FR-085); mechanical delegation with a hand-written control core below.
Code generated for gopls supervision (FR-085); mechanical delegation with a hand-written control core below.
ghtmx/routescmd
Package routescmd implements `ghtmx routes`: it prints the discovered route table for debugging why a binding did or did not resolve (FR-064).
Package routescmd implements `ghtmx routes`: it prints the discovered route table for debugging why a binding did or did not resolve (FR-064).
examples
crud
The task-67 reference CRUD application: the MVP acceptance demonstration.
The task-67 reference CRUD application: the MVP acceptance demonstration.
crud/cmd command
Command crud serves the crud example standalone.
Command crud serves the crud example standalone.
events
The events example: event declarations in page.ghtmx generate the only emission symbols (ghtmxgen.EmitItemSaved, ghtmxgen.EmitCartCleared) — an undeclared event has no symbol and cannot compile (FR-037).
The events example: event declarations in page.ghtmx generate the only emission symbols (ghtmxgen.EmitItemSaved, ghtmxgen.EmitCartCleared) — an undeclared event has no symbol and cannot compile (FR-037).
events/cmd command
Command events serves the events example standalone.
Command events serves the events example standalone.
fragments
The fragments example: one fragment declaration serves both render modes.
The fragments example: one fragment declaration serves both render modes.
fragments/cmd command
Command fragments serves the fragments example standalone.
Command fragments serves the fragments example standalone.
hello-world
The ghtmx walking skeleton: a minimal net/http application rendering a generated component, proving the full path from .ghtmx source to bytes in a browser (FR-090).
The ghtmx walking skeleton: a minimal net/http application rendering a generated component, proving the full path from .ghtmx source to bytes in a browser (FR-090).
hello-world/cmd command
Command helloworld serves the hello-world example standalone.
Command helloworld serves the hello-world example standalone.
htmx4-inheritance
The htmx4-inheritance example: htmx 4 inherits no attribute unless the ancestor says so.
The htmx4-inheritance example: htmx 4 inherits no attribute unless the ancestor says so.
htmx4-inheritance/cmd command
Command htmx4inheritance serves the htmx4-inheritance example standalone.
Command htmx4inheritance serves the htmx4-inheritance example standalone.
htmx4-inheritance/ghtmxgen
Package ghtmxgen is the central generated package: route path constants and typed route constructors, regenerated by ghtmx generate from the application's own route registrations.
Package ghtmxgen is the central generated package: route path constants and typed route constructors, regenerated by ghtmx generate from the application's own route registrations.
htmx4-query
The htmx4-query example: htmx 4 adds the QUERY method — safe and idempotent like GET, with the parameters in the body like POST — and morph swaps that update a region in place instead of replacing it.
The htmx4-query example: htmx 4 adds the QUERY method — safe and idempotent like GET, with the parameters in the body like POST — and morph swaps that update a region in place instead of replacing it.
htmx4-query/cmd command
Command htmx4query serves the htmx4-query example standalone.
Command htmx4query serves the htmx4-query example standalone.
htmx4-query/ghtmxgen
Package ghtmxgen is the central generated package: route path constants and typed route constructors, regenerated by ghtmx generate from the application's own route registrations.
Package ghtmxgen is the central generated package: route path constants and typed route constructors, regenerated by ghtmx generate from the application's own route registrations.
htmx4-status
The htmx4-status example: htmx 4 swaps every response by default, and hx-status:<code> decides per status where it goes.
The htmx4-status example: htmx 4 swaps every response by default, and hx-status:<code> decides per status where it goes.
htmx4-status/cmd command
Command htmx4status serves the htmx4-status example standalone.
Command htmx4status serves the htmx4-status example standalone.
htmx4-status/ghtmxgen
Package ghtmxgen is the central generated package: route path constants and typed route constructors, regenerated by ghtmx generate from the application's own route registrations.
Package ghtmxgen is the central generated package: route path constants and typed route constructors, regenerated by ghtmx generate from the application's own route registrations.
hx-bindings
The hx-bindings example exercises route-aware hx-* bindings end to end: a symbol binding folds a registered path into static markup, and a typed route constructor substitutes URL-escaped parameters (FR-020, FR-021, FR-023).
The hx-bindings example exercises route-aware hx-* bindings end to end: a symbol binding folds a registered path into static markup, and a typed route constructor substitutes URL-escaped parameters (FR-020, FR-021, FR-023).
hx-bindings/cmd command
Command hxbindings serves the hx-bindings example standalone.
Command hxbindings serves the hx-bindings example standalone.
hx-bindings/handlers
Package handlers holds the hx-bindings example's HTTP handlers.
Package handlers holds the hx-bindings example's HTTP handlers.
Package ghtmxgen is the central generated package: route path constants and typed route constructors, regenerated by ghtmx generate from the application's own route registrations.
Package ghtmxgen is the central generated package: route path constants and typed route constructors, regenerated by ghtmx generate from the application's own route registrations.
internal
analyzer
Package analyzer implements the ghtmx semantic analysis passes over the shared AST (constitution A2/A4): hx-* attribute validation against the pinned htmx surface, and — in later milestones — binding resolution, fragment classification, and the event registry.
Package analyzer implements the ghtmx semantic analysis passes over the shared AST (constitution A2/A4): hx-* attribute validation against the pinned htmx surface, and — in later milestones — binding resolution, fragment classification, and the event registry.
build
Package build holds the dependency graph and two-tier invalidation (FR-061, solution design M5).
Package build holds the dependency graph and two-tier invalidation (FR-061, solution design M5).
buildcache
Package buildcache is the on-disk content-hash build cache (solution design D6, NFR-001): generated output keyed by SHA-256 of the source content, salted with everything else that shapes the output — toolchain version, resolved configuration, and the route-binding state.
Package buildcache is the on-disk content-hash build cache (solution design D6, NFR-001): generated output keyed by SHA-256 of the source content, salted with everything else that shapes the output — toolchain version, resolved configuration, and the route-binding state.
config
Package config loads the ghtmx project configuration (ghtmx.json at the module root) and applies the flag > file > default precedence (FR-070, FR-071, FR-072, FR-073).
Package config loads the ghtmx project configuration (ghtmx.json at the module root) and applies the flag > file > default precedence (FR-070, FR-071, FR-072, FR-073).
diag
Package diag defines the ghtmx compiler's diagnostic model: stable identifiers, severities, source positions, and an accumulating sink.
Package diag defines the ghtmx compiler's diagnostic model: stable identifiers, severities, source positions, and an accumulating sink.
docsite
Package docsite holds the gates on the repository's documentation (NFR-013): that the getting-started guide's code still compiles and renders what it promises, and that the prose which restates a value defined in Go — the pinned htmx version above all — still matches it.
Package docsite holds the gates on the repository's documentation (NFR-013): that the getting-started guide's code still compiles and renders what it promises, and that the prose which restates a value defined in Go — the pinned htmx version above all — still matches it.
generator/central
Package central emits the central generated package (solution design D5): path constants for non-parameterised routes and typed constructor functions for parameterised routes (FR-021).
Package central emits the central generated package (solution design D5): path constants for non-parameterised routes and typed constructor functions for parameterised routes (FR-021).
htmxsurface
Package htmxsurface embeds the version-keyed htmx attribute surface set (DATA-006, solution design D8) and provides per-version validation of hx-* attribute names, values, and combinations.
Package htmxsurface embeds the version-keyed htmx attribute surface set (DATA-006, solution design D8) and provides per-version validation of hx-* attribute names, values, and combinations.
lsp/jsonrpc2
Package jsonrpc2 is an implementation of the JSON-RPC 2 specification for Go.
Package jsonrpc2 is an implementation of the JSON-RPC 2 specification for Go.
lsp/protocol
Package protocol implements Language Server Protocol specification in Go.
Package protocol implements Language Server Protocol specification in Go.
lsp/xcontext
Package xcontext is a package to offer the extra functionality we need from contexts that is not available from the standard context package.
Package xcontext is a package to offer the extra functionality we need from contexts that is not available from the standard context package.
release
Package release builds the versioned, checksummed release artifacts (NFR-010): one ghtmx binary per supported platform, archived with the license and README, plus a sha256 checksums file.
Package release builds the versioned, checksummed release artifacts (NFR-010): one ghtmx binary per supported platform, archived with the license and README, plus a sha256 checksums file.
release/cmd command
Command cmd builds the release artifacts (used by the release workflow; tests exercise the same builder on every CI run).
Command cmd builds the release artifacts (used by the release workflow; tests exercise the same builder on every CI run).
routes
Package routes builds the route table from application Go source by syntax-only static analysis (constitution A3, A3.1).
Package routes builds the route table from application Go source by syntax-only static analysis (constitution A3, A3.1).
Package routetable exposes the route table ghtmx derives from Go source, so a consuming project can assert in its own tests that the routes the toolchain believes in are the routes its framework really serves (FR-064).
Package routetable exposes the route table ghtmx derives from Go source, so a consuming project can assert in its own tests that the routes the toolchain believes in are the routes its framework really serves (FR-064).

Jump to

Keyboard shortcuts

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