h

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Jun 12, 2026 License: MIT Imports: 6 Imported by: 1

Documentation

Overview

Package h is a Go-native DSL for HTML composition.

Every element, attribute, and text node is a value implementing H, the single render-to-writer interface. Trees compose as ordinary Go values — `h.Div(h.ID("c"), h.H1(h.T("Counter")))` — and render with one Write per node, no per-render escaping, and no template engine.

Design properties:

  • one heap allocation per element (the element pointer + its variadic children slice fold into one object when the compiler can stack-promote the slice, otherwise two);
  • attributes are pre-escaped at construction so re-renders write their bytes verbatim;
  • text nodes carry the HTML-escaped payload directly;
  • rendering walks each child twice — attributes-pass then content-pass — using a concrete type switch rather than an interface-method indirection.

For fragments that don't depend on per-request state, Static pre-renders to bytes once and writes verbatim on every Render. For dynamic-tag escape hatches use Tag / NewTag. For shared composition use With to extend an existing element non-destructively.

Plugin authors emitting attribute-shaped output must use RawAttr: the attribute marker is unexported on purpose so external packages cannot inject raw bytes into the opening-tag region. See the on package for the canonical pattern.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IfStr added in v0.4.0

func IfStr(cond bool, s string) string

IfStr returns s if cond is true, "" otherwise. Pairs with Class and Styles for inline conditional fragments.

func NewTag added in v0.4.0

func NewTag(name string) func(children ...H) H

NewTag returns a reusable constructor for the given tag name. Use it when a custom element should share the call shape of the built-in constructors:

var SVG = h.NewTag("svg")
SVG(h.Attr("xmlns", "http://www.w3.org/2000/svg"), shapes...)

func NewVoidTag added in v0.4.0

func NewVoidTag(name string) func(children ...H) H

NewVoidTag is NewTag for void elements.

Types

type H

type H interface {
	Render(w io.Writer) error
}

H is anything that renders itself to an io.Writer.

func A

func A(children ...H) H

A renders the HTML <a> element.

func Abbr

func Abbr(children ...H) H

Abbr renders the HTML <abbr> element.

func Action added in v0.6.0

func Action(v string) H

Action emits the action attribute.

func Address

func Address(children ...H) H

Address renders the HTML <address> element.

func Alt added in v0.6.0

func Alt(v string) H

Alt emits the alt attribute.

func Area

func Area(children ...H) H

Area renders the void HTML <area> element.

func Aria added in v0.6.0

func Aria(name, value string) H

Aria is shorthand for `aria-<name>="value"` (HTML-escaped). Use it for accessibility attributes (`aria-label`, `aria-invalid`, …) instead of the stringly-typed Attr("aria-"+name, value).

func Article

func Article(children ...H) H

Article renders the HTML <article> element.

func Aside

func Aside(children ...H) H

Aside renders the HTML <aside> element.

func Attr

func Attr(name string, value ...string) H

Attr creates an attribute. A single value produces name="escaped"; no value produces a boolean attribute (`required`); more than one value panics.

func AttrNum added in v0.6.0

func AttrNum[T numeric](name string, v T) H

AttrNum emits `name="<v>"` for a numeric value, sparing callers the strconv/fmt conversion that string-valued Attr would require.

func Audio

func Audio(children ...H) H

Audio renders the HTML <audio> element.

func AutoComplete added in v0.6.0

func AutoComplete(v string) H

AutoComplete emits the autocomplete attribute.

func B

func B(children ...H) H

B renders the HTML <b> element.

func Base

func Base(children ...H) H

Base renders the void HTML <base> element.

func BlockQuote

func BlockQuote(children ...H) H

BlockQuote renders the HTML <blockquote> element.

func Body

func Body(children ...H) H

Body renders the HTML <body> element.

func Br

func Br(children ...H) H

Br renders the void HTML <br> element.

func Button

func Button(children ...H) H

Button renders the HTML <button> element.

func Canvas

func Canvas(children ...H) H

Canvas renders the HTML <canvas> element.

func Caption

func Caption(children ...H) H

Caption renders the HTML <caption> element.

func Charset added in v0.4.0

func Charset(v string) H

Charset emits the charset attribute.

func Checked added in v0.4.0

func Checked() H

Checked emits the boolean `checked` attribute.

func Cite

func Cite(children ...H) H

Cite renders the HTML <cite> element.

func Class

func Class(parts ...string) H

Class joins non-empty class names with spaces and emits a single class attribute. Returns nil when no class names remain so the attribute is omitted entirely.

h.Class("btn")                                  // single
h.Class("btn", "primary")                       // many
h.Class("btn", h.IfStr(active, "active"))       // conditional

func ClassMap added in v0.4.0

func ClassMap(m map[string]bool) H

ClassMap renders a class attribute that includes each key whose value is true. Keys are emitted in sorted order so the output is stable across renders.

func Classes deprecated added in v0.4.0

func Classes(parts ...string) H

Classes is an alias for Class retained so a slice already in hand can be spread without a rename. `Class(parts...)` is equivalent.

Deprecated: use Class. Classes will be removed in a future major release.

func Code

func Code(children ...H) H

Code renders the HTML <code> element.

func Col

func Col(children ...H) H

Col renders the void HTML <col> element.

func ColGroup

func ColGroup(children ...H) H

ColGroup renders the HTML <colgroup> element.

func ColSpan added in v0.6.0

func ColSpan(v string) H

ColSpan emits the colspan attribute.

func Content added in v0.4.0

func Content(v string) H

Content emits the content attribute.

func Data

func Data(name, value string) H

Data is shorthand for `data-<name>="value"`. Specialised over Attr("data-"+name, value) to skip the per-call name-prefix concatenation.

func DataClass added in v0.4.0

func DataClass(className, format string, args ...any) H

DataClass conditionally adds/removes a CSS class.

func DataIgnoreMorph added in v0.2.0

func DataIgnoreMorph() H

DataIgnoreMorph tells datastar to skip morphing this element on patch.

func DataInit added in v0.2.0

func DataInit(format string, args ...any) H

DataInit runs an expression once when the page loads.

func DataList

func DataList(children ...H) H

DataList renders the HTML <datalist> element.

func DataOnClick added in v0.4.0

func DataOnClick(format string, args ...any) H

DataOnClick attaches a datastar click handler. Use for frontend-only signal mutations; for server actions prefer the `on` package.

func DataShow added in v0.4.0

func DataShow(format string, args ...any) H

DataShow conditionally shows/hides the element based on the expression's truthiness.

func Dd

func Dd(children ...H) H

Dd renders the HTML <dd> element.

func Del

func Del(children ...H) H

Del renders the HTML <del> element.

func Details

func Details(children ...H) H

Details renders the HTML <details> element.

func Dfn

func Dfn(children ...H) H

Dfn renders the HTML <dfn> element.

func Dialog

func Dialog(children ...H) H

Dialog renders the HTML <dialog> element.

func Disabled added in v0.4.0

func Disabled() H

Disabled emits the boolean `disabled` attribute.

func Div

func Div(children ...H) H

Div renders the HTML <div> element.

func Dl

func Dl(children ...H) H

Dl renders the HTML <dl> element.

func Dt

func Dt(children ...H) H

Dt renders the HTML <dt> element.

func Each added in v0.4.0

func Each[T any](items []T, fn func(T) H) H

Each renders one node per element of items.

func EachIndexed added in v0.4.0

func EachIndexed[T any](items []T, fn func(i int, v T) H) H

EachIndexed is Each with the element index passed alongside the value.

func EachSeq added in v0.4.0

func EachSeq[T any](seq iter.Seq[T], fn func(T) H) H

EachSeq renders one node per value drawn from a Go 1.23 iter.Seq.

func EachSeq2 added in v0.4.0

func EachSeq2[K, V any](seq iter.Seq2[K, V], fn func(K, V) H) H

EachSeq2 renders one node per (K, V) pair drawn from a Go 1.23 iter.Seq2.

func Em

func Em(children ...H) H

Em renders the HTML <em> element.

func Embed

func Embed(children ...H) H

Embed renders the void HTML <embed> element.

func FieldSet

func FieldSet(children ...H) H

FieldSet renders the HTML <fieldset> element.

func FigCaption

func FigCaption(children ...H) H

FigCaption renders the HTML <figcaption> element.

func Figure

func Figure(children ...H) H

Figure renders the HTML <figure> element.

func Footer(children ...H) H

Footer renders the HTML <footer> element.

func For added in v0.4.0

func For(v string) H

For emits the for attribute.

func Form

func Form(children ...H) H

Form renders the HTML <form> element.

func Fragment added in v0.4.0

func Fragment(items ...H) H

Fragment bundles many nodes into one H. Use it when a function whose signature returns a single H needs to yield several:

return Fragment(H2(T("title")), Hr())
return Fragment(items...)

Attribute arguments (ID, Class, on.*, …) panic at construction: a fragment has no opening tag to put them in, so they were previously dropped without a trace — a programming mistake better caught where the bad call is written.

The returned node aliases items — there is no defensive copy. Callers must not mutate items after handing it to Fragment.

func H1

func H1(children ...H) H

H1 renders the HTML <h1> element.

func H2

func H2(children ...H) H

H2 renders the HTML <h2> element.

func H3

func H3(children ...H) H

H3 renders the HTML <h3> element.

func H4

func H4(children ...H) H

H4 renders the HTML <h4> element.

func H5

func H5(children ...H) H

H5 renders the HTML <h5> element.

func H6

func H6(children ...H) H

H6 renders the HTML <h6> element.

func HGroup added in v0.4.0

func HGroup(children ...H) H

HGroup renders the HTML <hgroup> element.

func HTML

func HTML(children ...H) H

HTML renders the HTML <html> element.

func HTML5

func HTML5(p HTML5Props) H

HTML5 returns a fully formed HTML5 document. The injected datastar script tag matches the h.HTML5 surface so the runtime can serve the same fragment regardless of which package built it.

func Head(children ...H) H

Head renders the HTML <head> element.

func Header(children ...H) H

Header renders the HTML <header> element.

func Height added in v0.6.0

func Height(v string) H

Height emits the height attribute.

func Hr

func Hr(children ...H) H

Hr renders the void HTML <hr> element.

func Href

func Href(v string) H

One shorthand per common HTML attribute — each emits `name="value"` (HTML-escaped) via [buildAttr]. For an attribute without a shorthand use Attr; for data-* use Data; for boolean attributes see Selected, Checked, Required, Disabled. Href emits the href attribute.

func I

func I(children ...H) H

I renders the HTML <i> element.

func ID

func ID(v string) H

ID emits the id attribute.

func IFrame

func IFrame(children ...H) H

IFrame renders the HTML <iframe> element.

func If

func If(condition bool, n H) H

If returns n when condition is true, otherwise nil — which renders as nothing. Both branches are evaluated eagerly; use When if constructing n is expensive or has side effects you only want when condition holds.

func IfElse added in v0.4.0

func IfElse(condition bool, then, els H) H

IfElse picks between two pre-built branches. Both are constructed eagerly — use WhenElse if construction is expensive.

func Img

func Img(children ...H) H

Img renders the void HTML <img> element.

func Input

func Input(children ...H) H

Input renders the void HTML <input> element.

func Ins

func Ins(children ...H) H

Ins renders the HTML <ins> element.

func Kbd

func Kbd(children ...H) H

Kbd renders the HTML <kbd> element.

func Label

func Label(children ...H) H

Label renders the HTML <label> element.

func Lang added in v0.4.0

func Lang(v string) H

Lang emits the lang attribute.

func Legend

func Legend(children ...H) H

Legend renders the HTML <legend> element.

func Li

func Li(children ...H) H

Li renders the HTML <li> element.

func Link(children ...H) H

Link renders the void HTML <link> element.

func Main

func Main(children ...H) H

Main renders the HTML <main> element.

func Mark

func Mark(children ...H) H

Mark renders the HTML <mark> element.

func Max added in v0.2.0

func Max(v string) H

Max emits the max attribute.

func MaxLength added in v0.6.0

func MaxLength(n int) H

MaxLength emits the maxlength attribute.

func MaxNum added in v0.6.0

func MaxNum[T numeric](v T) H

MaxNum is the numeric form of Max for range/number inputs.

func Maybe added in v0.4.0

func Maybe[T comparable](v T, fn func(T) H) H

Maybe renders fn(v) only when v differs from its zero value, so optional fields and pointer-style data render cleanly without an explicit guard at every call site. T must be [comparable] because the zero check is `v == zero` — uncomparable types (slices, maps, funcs) fail at compile time rather than via a generics error at instantiation.

h.Maybe(user.Email, func(s string) h.H {
    return h.P("email: ", s)
})

func Meta

func Meta(children ...H) H

Meta renders the void HTML <meta> element.

func Meter

func Meter(children ...H) H

Meter renders the HTML <meter> element.

func Method added in v0.6.0

func Method(v string) H

Method emits the method attribute.

func Min added in v0.2.0

func Min(v string) H

Min emits the min attribute.

func MinLength added in v0.6.0

func MinLength(n int) H

MinLength emits the minlength attribute.

func MinNum added in v0.6.0

func MinNum[T numeric](v T) H

MinNum is the numeric form of Min for range/number inputs.

func Name added in v0.4.0

func Name(v string) H

Name emits the name attribute.

func Nav(children ...H) H

Nav renders the HTML <nav> element.

func NoScript

func NoScript(children ...H) H

NoScript renders the HTML <noscript> element.

func Object

func Object(children ...H) H

Object renders the HTML <object> element.

func Ol

func Ol(children ...H) H

Ol renders the HTML <ol> element.

func OptGroup

func OptGroup(children ...H) H

OptGroup renders the HTML <optgroup> element.

func Option

func Option(children ...H) H

Option renders the HTML <option> element.

func P

func P(children ...H) H

P renders the HTML <p> element.

func Pattern added in v0.6.0

func Pattern(v string) H

Pattern emits the pattern attribute — a regex for native client-side input validation. Pairs with Required for zero-round-trip constraint checks.

func Picture

func Picture(children ...H) H

Picture renders the HTML <picture> element.

func Placeholder

func Placeholder(v string) H

Placeholder emits the placeholder attribute.

func Pre

func Pre(children ...H) H

Pre renders the HTML <pre> element.

func Progress

func Progress(children ...H) H

Progress renders the HTML <progress> element.

func Q

func Q(children ...H) H

Q renders the HTML <q> element.

func Raw

func Raw(s string) H

Raw emits s verbatim — the caller is responsible for HTML safety.

func Rel

func Rel(v string) H

Rel emits the rel attribute.

func Required added in v0.4.0

func Required() H

Required emits the boolean `required` attribute.

func Role

func Role(v string) H

Role emits the role attribute.

func RowSpan added in v0.6.0

func RowSpan(v string) H

RowSpan emits the rowspan attribute.

func S

func S(children ...H) H

S renders the HTML <s> element.

func Samp

func Samp(children ...H) H

Samp renders the HTML <samp> element.

func Script

func Script(children ...H) H

Script renders the HTML <script> element.

func Section

func Section(children ...H) H

Section renders the HTML <section> element.

func Select

func Select(children ...H) H

Select renders the HTML <select> element.

func Selected added in v0.4.0

func Selected() H

Selected emits the boolean `selected` attribute.

func Small

func Small(children ...H) H

Small renders the HTML <small> element.

func Source

func Source(children ...H) H

Source renders the void HTML <source> element.

func Span

func Span(children ...H) H

Span renders the HTML <span> element.

func Src

func Src(v string) H

Src emits the src attribute.

func Static added in v0.4.0

func Static(n H) H

Static pre-renders n into a byte slice and returns an H that writes those bytes on every Render. Use it for fragments that don't depend on per-request state — site headers, navigation, layout chrome — so they stop allocating across reloads.

Capturing a subtree that embeds a RawAttr (or any other node derived from per-request data) is almost certainly a bug: the bytes are frozen at construction and will keep emitting the original values regardless of later state. Reserve Static for truly static content built at package-init time.

Panics if n.Render returns an error during pre-render; a Static node is built at package-init time where the only realistic failure is a misconfigured writer.

func Step added in v0.2.0

func Step(v string) H

Step emits the step attribute.

func StepNum added in v0.6.0

func StepNum[T numeric](v T) H

StepNum is the numeric form of Step for range/number inputs.

func Strong

func Strong(children ...H) H

Strong renders the HTML <strong> element.

func Style

func Style(v string) H

Style emits an inline `style="..."` attribute. For the `<style>...</style>` element use StyleEl.

func StyleEl

func StyleEl(children ...H) H

StyleEl renders the HTML <style> element.

func Styles added in v0.4.0

func Styles(parts ...string) H

Styles joins non-empty CSS declarations with `;` and emits one inline style attribute. Skip-on-empty makes inline conditionals natural:

h.Styles("flex:1", h.IfStr(done, "text-decoration:line-through"))

func Sub

func Sub(children ...H) H

Sub renders the HTML <sub> element.

func Summary

func Summary(children ...H) H

Summary renders the HTML <summary> element.

func Sup

func Sup(children ...H) H

Sup renders the HTML <sup> element.

func Switch added in v0.4.0

func Switch[K comparable](value K, cases ...SwitchCase[K]) H

Switch renders the first matching SwitchCase and nothing else.

value and every Case key share the comparable type K, so a mismatched case is a compile error. Note Go's comparable admits interface and comparable-struct types whose comparison can still panic at runtime if a value carries a non-comparable dynamic type — for tab-style branching on such a value, project it to a simple key first (e.g. a tag string or enum) and Switch on that.

func T added in v0.4.0

func T(s string) H

T is a brevity alias for Text. The short name matters at call sites where many small text nodes nest inside one-letter element constructors — `h.H1(h.T("Counter"))` reads cleaner than `h.H1(h.Text("Counter"))` without sacrificing static typing.

func TBody

func TBody(children ...H) H

TBody renders the HTML <tbody> element.

func TFoot

func TFoot(children ...H) H

TFoot renders the HTML <tfoot> element.

func THead

func THead(children ...H) H

THead renders the HTML <thead> element.

func TabIndex added in v0.6.0

func TabIndex(v string) H

TabIndex emits the tabindex attribute.

func Table

func Table(children ...H) H

Table renders the HTML <table> element.

func Tag added in v0.4.0

func Tag(name string, children ...H) H

Tag emits a custom non-void element. Use it for tags absent from the static constructor list (web components, SVG primitives, etc.). The tag name is written verbatim — callers must supply a valid HTML element name; nothing here validates it.

func Target added in v0.6.0

func Target(v string) H

Target emits the target attribute.

func Td

func Td(children ...H) H

Td renders the HTML <td> element.

func Template

func Template(children ...H) H

Template renders the HTML <template> element.

func Text

func Text(s string) H

Text creates an HTML-escaped text node. When the input contains no characters that need escaping, the node carries the input string verbatim — no byte copy.

func Textarea

func Textarea(children ...H) H

Textarea renders the HTML <textarea> element.

func Textf

func Textf(format string, a ...any) H

Textf formats and escapes once at construction.

func Th

func Th(children ...H) H

Th renders the HTML <th> element.

func Time

func Time(children ...H) H

Time renders the HTML <time> element.

func Title

func Title(v string) H

Title emits <title>v</title> with v HTML-escaped. Defined alongside element constructors because it produces an element node, not an attribute.

func Tr

func Tr(children ...H) H

Tr renders the HTML <tr> element.

func Type

func Type(v string) H

Type emits the type attribute.

func U

func U(children ...H) H

U renders the HTML <u> element.

func Ul

func Ul(children ...H) H

Ul renders the HTML <ul> element.

func Value

func Value(v string) H

Value emits the value attribute.

func ValueNum added in v0.6.0

func ValueNum[T numeric](v T) H

ValueNum is the numeric form of Value for range/number inputs.

func Var

func Var(children ...H) H

Var renders the HTML <var> element.

func Video

func Video(children ...H) H

Video renders the HTML <video> element.

func VoidTag added in v0.4.0

func VoidTag(name string, children ...H) H

VoidTag emits a custom void element (no closing tag, content children dropped at render time). The tag name is written verbatim — callers must supply a valid HTML element name; nothing here validates it.

func Wbr

func Wbr(children ...H) H

Wbr renders the void HTML <wbr> element.

func When added in v0.4.0

func When(condition bool, build func() H) H

When is If with a builder so the node is constructed lazily.

func WhenElse added in v0.4.0

func WhenElse(condition bool, then, els func() H) H

WhenElse is IfElse with lazy builders — only the winning branch runs. Either builder may be nil; a nil builder for the winning branch renders nothing.

func Width added in v0.6.0

func Width(v string) H

Width emits the width attribute.

func With added in v0.4.0

func With(base H, more ...H) H

With returns a copy of base extended with additional children. It makes component composition compose without forcing every component signature to take a variadic — e.g. a Card(body) constructor can still gain an extra class or click handler at the call site:

h.With(Card(myBody), on.Click(open))

When base is not an *element (text, group, attribute, raw fragment, …) With falls back to a plain group so the result still renders the base followed by more. In that fallback path, attribute children bubble to the wrapping element via group semantics (the renderer skips attributes at the group top level and the parent element consumes them); they do not attach to base itself.

type HTML5Props

type HTML5Props struct {
	Title       string
	Description string
	Language    string
	Head        []H
	Body        []H
	HTMLAttrs   []H
}

HTML5Props defines properties for HTML5 pages. Title is always set; Description and Language are emitted only when their strings are non-empty.

type RawAttr added in v0.4.0

type RawAttr []byte

RawAttr is a pre-rendered attribute fragment (leading space, name, optional `="escaped-value"`). It implements H as an attribute so the element renderer emits it inside the opening tag, and writes its bytes verbatim on every Render — no per-render escape.

The bytes are owned by the caller; do not mutate them after passing the value to H consumers.

func (RawAttr) Render added in v0.4.0

func (a RawAttr) Render(w io.Writer) error

type SwitchCase added in v0.4.0

type SwitchCase[K comparable] struct {
	// contains filtered or unexported fields
}

SwitchCase pairs a key with the node to render when Switch's value matches the key. Build with Case / Default.

func Case added in v0.4.0

func Case[K comparable](key K, node H) SwitchCase[K]

Case returns a SwitchCase that fires when Switch's value equals key.

func Default added in v0.4.0

func Default[K comparable](node H) SwitchCase[K]

Default returns a SwitchCase that fires when no other case matches. At most one Default per Switch is honoured (the first one wins).

K cannot be inferred from the argument, so it is spelled explicitly at the call site: h.Default[Status](unknownView).

Jump to

Keyboard shortcuts

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