h

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

Package h provides a low-level streaming HTML writer and a declarative builder API for programmatic HTML generation.

Index

Constants

This section is empty.

Variables

View Source
var ErrUnknownTagToClose = errors.New("attempted to close tag not opened")

ErrUnknownTagToClose is returned when attempting to close a tag that was not opened.

Functions

func Render

func Render(w io.Writer, b Builder) error

Render writes the HTML representation of the given Builder to w. Returns nil if b is nil.

func RenderBytes

func RenderBytes(b Builder) []byte

RenderBytes renders the Builder and returns the result as a byte slice. Returns nil if b is nil. Panics if rendering fails.

html := h.RenderBytes(h.Div(h.Text("Hello")))

func RenderIndent

func RenderIndent(w io.Writer, indent string, b Builder) error

RenderIndent writes the HTML representation of the given Builder to w with indentation for readability. The indent parameter specifies the string to use for each indentation level (e.g., " " for two spaces or "\t" for tabs). Returns nil if b is nil.

func RenderString

func RenderString(b Builder) string

RenderString renders the Builder and returns the result as a string. Returns an empty string if b is nil. Panics if rendering fails.

html := h.RenderString(h.Div(h.Text("Hello")))

Types

type Attribute

type Attribute struct {
	Name  string
	Value string
}

Attribute represents a single HTML attribute as a name-value pair.

func Attr

func Attr(name, value string) Attribute

Attr creates a new Attribute with the given name and value. Panics if name is empty.

func AttrIf

func AttrIf(cond bool, name, value string) Attribute

AttrIf returns an Attribute if cond is true, otherwise returns a zero Attribute which will be ignored during rendering. This is useful for conditionally including attributes:

h.Button(
    h.AttrIf(isDisabled, "disabled", ""),
    h.AttrIf(isPrimary, "class", "btn-primary"),
    h.Text("Submit"),
)

type Attributes

type Attributes []Attribute

Attributes is a slice of Attribute values representing HTML element attributes. It provides methods for getting, setting, and deleting attributes by name.

func Attrs

func Attrs(kv ...string) Attributes

Attrs creates an Attributes slice from alternating key-value string pairs. Panics if an odd number of arguments is provided or if any key is empty.

Example: Attrs("href", "/home", "class", "nav-link")

func AttrsMap

func AttrsMap(m map[string]string) Attributes

AttrsMap creates an Attributes slice from a map of key-value pairs. Keys are sorted alphabetically for deterministic output.

func (*Attributes) Delete

func (a *Attributes) Delete(key string)

Delete removes the attribute with the given name if it exists.

func (*Attributes) Get

func (a *Attributes) Get(key string) (string, bool)

Get returns the value for the given attribute name and true if found, or an empty string and false if not found.

func (*Attributes) Index

func (a *Attributes) Index(key string) int

Index returns the index of the attribute with the given name, or -1 if not found.

func (*Attributes) Merge

func (a *Attributes) Merge(b Attributes)

Merge merges attributes from b into a. Values from b take precedence over existing values in a for attributes with the same name.

func (*Attributes) Set

func (a *Attributes) Set(key, value string)

Set sets the value for the given attribute name. If the attribute already exists, its value is updated; otherwise, a new attribute is appended.

func (*Attributes) SetDefault

func (a *Attributes) SetDefault(key, value string)

SetDefault sets the value for the given attribute name only if the attribute does not already exist.

type Builder

type Builder interface {
	TagArg
	Build(w *Writer) error
}

Builder is the interface implemented by all HTML node builders. Implementations write their HTML representation to the provided Writer.

func A

func A(args ...TagArg) Builder

A creates an <a> element for hyperlinks.

func Abbr

func Abbr(args ...TagArg) Builder

Abbr creates an <abbr> element for abbreviations.

func Address

func Address(args ...TagArg) Builder

Address creates an <address> element for contact information.

func Area

func Area(args ...TagArg) Builder

Area creates an <area> element for image map areas.

func Article

func Article(args ...TagArg) Builder

Article creates an <article> element for self-contained content.

func Aside

func Aside(args ...TagArg) Builder

Aside creates an <aside> element for tangentially related content.

func Audio

func Audio(args ...TagArg) Builder

Audio creates an <audio> element for sound content.

func B

func B(args ...TagArg) Builder

B creates a <b> element for bold text.

func Base

func Base(args ...TagArg) Builder

Base creates a <base> element for document base URL.

func Bdi

func Bdi(args ...TagArg) Builder

Bdi creates a <bdi> element for bidirectional text isolation.

func Bdo

func Bdo(args ...TagArg) Builder

Bdo creates a <bdo> element for bidirectional text override.

func Blockquote

func Blockquote(args ...TagArg) Builder

Blockquote creates a <blockquote> element for extended quotations.

func Body

func Body(args ...TagArg) Builder

Body creates a <body> element as the document's sectioning root.

func Br

func Br(args ...TagArg) Builder

Br creates a <br> element for line breaks.

func Button

func Button(args ...TagArg) Builder

Button creates a <button> element for clickable buttons.

func Canvas

func Canvas(args ...TagArg) Builder

Canvas creates a <canvas> element for graphics rendering.

func Caption

func Caption(args ...TagArg) Builder

Caption creates a <caption> element for table captions.

func Cite

func Cite(args ...TagArg) Builder

Cite creates a <cite> element for citations.

func Code

func Code(args ...TagArg) Builder

Code creates a <code> element for code fragments.

func Col

func Col(args ...TagArg) Builder

Col creates a <col> element for table column properties.

func Colgroup

func Colgroup(args ...TagArg) Builder

Colgroup creates a <colgroup> element for table column groups.

func Compile

func Compile(b Builder) (Builder, error)

Compile pre-renders a Builder to bytes for faster subsequent renders. The resulting Builder writes the cached bytes directly without tree traversal, achieving performance comparable to html/template.

Use Compile for static content that is rendered frequently:

// Compile once at startup
header, err := h.Compile(h.Header(h.H1(h.Text("My Site"))))
if err != nil {
	// handle error
}

// Fast renders afterward
if err := h.Render(w, header); err != nil {
	// handle error
}

Note: Compiled builders ignore indentation settings since the output is pre-computed. For pretty-printed cached output, render with RenderIndent first, then compile the result using Raw.

func CustomElement

func CustomElement(name string, args ...TagArg) Builder

CustomElement creates a custom HTML element with the given tag name.

func Data

func Data(args ...TagArg) Builder

Data creates a <data> element for machine-readable content.

func Datalist

func Datalist(args ...TagArg) Builder

Datalist creates a <datalist> element for input suggestions.

func Dd

func Dd(args ...TagArg) Builder

Dd creates a <dd> element for description list definitions.

func Del

func Del(args ...TagArg) Builder

Del creates a <del> element for deleted text.

func Details

func Details(args ...TagArg) Builder

Details creates a <details> element for disclosure widgets.

func Dfn

func Dfn(args ...TagArg) Builder

Dfn creates a <dfn> element for definitions.

func Dialog

func Dialog(args ...TagArg) Builder

Dialog creates a <dialog> element for modal dialogs.

func Div

func Div(args ...TagArg) Builder

Div creates a <div> element as a generic container.

func Dl

func Dl(args ...TagArg) Builder

Dl creates a <dl> element for description lists.

func Dt

func Dt(args ...TagArg) Builder

Dt creates a <dt> element for description list terms.

func Em

func Em(args ...TagArg) Builder

Em creates an <em> element for emphasized text.

func Embed

func Embed(args ...TagArg) Builder

Embed creates an <embed> element for external content.

func Fieldset

func Fieldset(args ...TagArg) Builder

Fieldset creates a <fieldset> element for form field groups.

func Figcaption

func Figcaption(args ...TagArg) Builder

Figcaption creates a <figcaption> element for figure captions.

func Figure

func Figure(args ...TagArg) Builder

Figure creates a <figure> element for self-contained content with optional caption.

func First

func First(b ...Builder) Builder

First returns the first non-nil Builder from the provided arguments. Returns nil if all arguments are nil or no arguments are provided. Useful for fallback content patterns:

h.Div(
    h.First(customHeader, defaultHeader, h.Text("Untitled")),
)
func Footer(args ...TagArg) Builder

Footer creates a <footer> element for footer content.

func ForEach

func ForEach[X any](s iter.Seq[X], fn func(X) Builder) Builder

ForEach creates a Builder that lazily maps over an iterator sequence, rendering each resulting Builder in order. Nil builders returned by the mapping function are skipped.

The iterator is consumed during rendering, not when ForEach is called.

h.Ul(
    h.ForEach(slices.Values(items), func(item Item) h.Builder {
        return h.Li(h.Text(item.Name))
    }),
)

func ForEach2

func ForEach2[X, Y any](s iter.Seq2[X, Y], fn func(X, Y) Builder) Builder

ForEach2 creates a Builder that lazily maps over a two-value iterator sequence, rendering each resulting Builder in order. Nil builders returned by the mapping function are skipped.

The iterator is consumed during rendering, not when ForEach2 is called. Common use cases include maps.All() for key-value pairs or slices.All() for index-value pairs:

h.Dl(
    h.ForEach2(maps.All(definitions), func(term, def string) h.Builder {
        return h.Fragment(h.Dt(h.Text(term)), h.Dd(h.Text(def)))
    }),
)

func Form

func Form(args ...TagArg) Builder

Form creates a <form> element for user input forms.

func Fragment

func Fragment(children ...Builder) Builder

Fragment creates a Builder that renders its children without a wrapping element.

func H1

func H1(args ...TagArg) Builder

H1 creates an <h1> heading element.

func H2

func H2(args ...TagArg) Builder

H2 creates an <h2> heading element.

func H3

func H3(args ...TagArg) Builder

H3 creates an <h3> heading element.

func H4

func H4(args ...TagArg) Builder

H4 creates an <h4> heading element.

func H5

func H5(args ...TagArg) Builder

H5 creates an <h5> heading element.

func H6

func H6(args ...TagArg) Builder

H6 creates an <h6> heading element.

func Head(args ...TagArg) Builder

Head creates a <head> element for document metadata.

func Header(args ...TagArg) Builder

Header creates a <header> element for introductory content.

func Hgroup

func Hgroup(args ...TagArg) Builder

Hgroup creates an <hgroup> element for heading groups.

func Hr

func Hr(args ...TagArg) Builder

Hr creates an <hr> element for thematic breaks.

func Html

func Html(args ...TagArg) Builder

Html creates the root <html> element with DOCTYPE declaration. Sets lang="en" by default if not specified in attributes.

func I

func I(args ...TagArg) Builder

I creates an <i> element for idiomatic text.

func If

func If(cond bool, ifTrue, ifElse Builder) Builder

If returns ifTrue if cond is true, otherwise returns ifElse. This enables conditional rendering in builder expressions:

h.Div(
    h.If(user.IsAdmin,
        h.Span(h.Text("Admin")),
        h.Span(h.Text("User")),
    ),
)

func Iframe

func Iframe(args ...TagArg) Builder

Iframe creates an <iframe> element for nested browsing contexts.

func Img

func Img(args ...TagArg) Builder

Img creates an <img> element for images.

func Input

func Input(args ...TagArg) Builder

Input creates an <input> element for form inputs.

func Ins

func Ins(args ...TagArg) Builder

Ins creates an <ins> element for inserted text.

func Kbd

func Kbd(args ...TagArg) Builder

Kbd creates a <kbd> element for keyboard input.

func Label

func Label(args ...TagArg) Builder

Label creates a <label> element for form control labels.

func Legend

func Legend(args ...TagArg) Builder

Legend creates a <legend> element for fieldset captions.

func Li

func Li(args ...TagArg) Builder

Li creates an <li> element for list items.

func Link(args ...TagArg) Builder

Link creates a <link> element for external resources.

func Main

func Main(args ...TagArg) Builder

Main creates a <main> element for the dominant content.

func Map

func Map(args ...TagArg) Builder

Map creates a <map> element for image maps.

func Mark

func Mark(args ...TagArg) Builder

Mark creates a <mark> element for highlighted text.

func Math

func Math(args ...TagArg) Builder

Math creates a <math> element for MathML content.

func Menu(args ...TagArg) Builder

Menu creates a <menu> element for toolbar menus.

func Meta

func Meta(args ...TagArg) Builder

Meta creates a <meta> element for document metadata.

func Meter

func Meter(args ...TagArg) Builder

Meter creates a <meter> element for scalar measurements.

func MustCompile

func MustCompile(b Builder) Builder

MustCompile is like Compile but panics if compilation fails. It is intended for use during initialization when errors should be caught immediately.

// Compile once at startup
header := h.MustCompile(h.Header(h.H1(h.Text("My Site"))))
func Nav(args ...TagArg) Builder

Nav creates a <nav> element for navigation links.

func Noscript

func Noscript(args ...TagArg) Builder

Noscript creates a <noscript> element for fallback content.

func Object

func Object(args ...TagArg) Builder

Object creates an <object> element for external resources.

func Ol

func Ol(args ...TagArg) Builder

Ol creates an <ol> element for ordered lists.

func Optgroup

func Optgroup(args ...TagArg) Builder

Optgroup creates an <optgroup> element for option groups.

func Option

func Option(args ...TagArg) Builder

Option creates an <option> element for select options.

func Output

func Output(args ...TagArg) Builder

Output creates an <output> element for calculation results.

func P

func P(args ...TagArg) Builder

P creates a <p> element for paragraphs.

func Picture

func Picture(args ...TagArg) Builder

Picture creates a <picture> element for responsive images.

func Portal

func Portal(args ...TagArg) Builder

Portal creates a <portal> element for embedded pages.

func Pre

func Pre(args ...TagArg) Builder

Pre creates a <pre> element for preformatted text.

func Progress

func Progress(args ...TagArg) Builder

Progress creates a <progress> element for progress indicators.

func Q

func Q(args ...TagArg) Builder

Q creates a <q> element for inline quotations.

func Raw

func Raw(value string) Builder

Raw creates a Builder that renders unescaped HTML content. Use with caution as this can introduce XSS vulnerabilities.

func Rp

func Rp(args ...TagArg) Builder

Rp creates an <rp> element for ruby fallback parentheses.

func Rt

func Rt(args ...TagArg) Builder

Rt creates an <rt> element for ruby text.

func Ruby

func Ruby(args ...TagArg) Builder

Ruby creates a <ruby> element for ruby annotations.

func S

func S(args ...TagArg) Builder

S creates an <s> element for strikethrough text.

func Samp

func Samp(args ...TagArg) Builder

Samp creates a <samp> element for sample output.

func Script

func Script(args ...TagArg) Builder

Script creates a <script> element for JavaScript.

func Search(args ...TagArg) Builder

Search creates a <search> element for search functionality.

func Section

func Section(args ...TagArg) Builder

Section creates a <section> element for thematic content grouping.

func Select

func Select(args ...TagArg) Builder

Select creates a <select> element for dropdown lists.

func Slot

func Slot(args ...TagArg) Builder

Slot creates a <slot> element for web component content distribution.

func Small

func Small(args ...TagArg) Builder

Small creates a <small> element for side comments.

func Source

func Source(args ...TagArg) Builder

Source creates a <source> element for media sources.

func Span

func Span(args ...TagArg) Builder

Span creates a <span> element as a generic inline container.

func Strong

func Strong(args ...TagArg) Builder

Strong creates a <strong> element for strong importance.

func Style

func Style(args ...TagArg) Builder

Style creates a <style> element for embedded CSS.

func Sub

func Sub(args ...TagArg) Builder

Sub creates a <sub> element for subscript text.

func Summary

func Summary(args ...TagArg) Builder

Summary creates a <summary> element for details disclosure.

func Sup

func Sup(args ...TagArg) Builder

Sup creates a <sup> element for superscript text.

func Svg

func Svg(args ...TagArg) Builder

Svg creates an <svg> element for SVG graphics.

func Table

func Table(args ...TagArg) Builder

Table creates a <table> element for tabular data.

func Tbody

func Tbody(args ...TagArg) Builder

Tbody creates a <tbody> element for table body content.

func Td

func Td(args ...TagArg) Builder

Td creates a <td> element for table data cells.

func Template

func Template(args ...TagArg) Builder

Template creates a <template> element for client-side content templates.

func Text

func Text(value string) Builder

Text creates a Builder that renders HTML-escaped text content.

func Textarea

func Textarea(args ...TagArg) Builder

Textarea creates a <textarea> element for multi-line text input.

func Textf

func Textf(format string, args ...any) Builder

Textf creates a Builder that renders HTML-escaped formatted text. Arguments are formatted according to the format specifier using fmt.Sprintf.

h.Span(h.Textf("Hello, %s!", name))

func Tfoot

func Tfoot(args ...TagArg) Builder

Tfoot creates a <tfoot> element for table footer content.

func Th

func Th(args ...TagArg) Builder

Th creates a <th> element for table header cells.

func Thead

func Thead(args ...TagArg) Builder

Thead creates a <thead> element for table header content.

func Time

func Time(args ...TagArg) Builder

Time creates a <time> element for dates and times.

func Title

func Title(args ...TagArg) Builder

Title creates a <title> element for the document title.

func Tr

func Tr(args ...TagArg) Builder

Tr creates a <tr> element for table rows.

func Track

func Track(args ...TagArg) Builder

Track creates a <track> element for media text tracks.

func U

func U(args ...TagArg) Builder

U creates a <u> element for underlined text.

func Ul

func Ul(args ...TagArg) Builder

Ul creates a <ul> element for unordered lists.

func Unless

func Unless(cond bool, ifFalse Builder) Builder

Unless returns ifFalse if cond is false, otherwise returns nil. This is the inverse of When, useful for "render unless" patterns:

h.Div(
    h.Unless(user.IsAdmin, h.Span(h.Text("(Restricted)"))),
)

func Var

func Var(args ...TagArg) Builder

Var creates a <var> element for variable names.

func Video

func Video(args ...TagArg) Builder

Video creates a <video> element for video content.

func Wbr

func Wbr(args ...TagArg) Builder

Wbr creates a <wbr> element for word break opportunities.

func When

func When(cond bool, ifTrue Builder) Builder

When returns ifTrue if cond is true, otherwise returns nil. Nil builders are safely skipped during rendering. This is a convenience wrapper around If for cases without an else branch:

h.Div(
    h.When(showWarning, h.Span(h.Text("Warning!"))),
)

type CompiledTemplate

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

CompiledTemplate is a pre-computed template with parameter placeholders. Created by CompileParams, it stores static HTML segments and parameter positions.

func CompileParams

func CompileParams(b Builder) (*CompiledTemplate, error)

CompileParams pre-computes a Builder with Param placeholders for dynamic content. Static HTML is pre-rendered into segments, with params marking where dynamic content will be inserted at render time.

title := h.NewParam("title")
content := h.NewParam("content")

tmpl, err := h.CompileParams(h.Div(
    h.H1(title),
    h.P(content),
))
if err != nil {
	// handle error
}

// Render with values
tmpl.Render(w,
    title.Value(h.Text("Hello World")),
    content.Value(h.Text("Welcome!")),
)

func MustCompileParams

func MustCompileParams(b Builder) *CompiledTemplate

MustCompileParams is like CompileParams but panics if compilation fails. It is intended for use during initialization when errors should be caught immediately.

title := h.NewParam("title")
content := h.NewParam("content")

tmpl := h.MustCompileParams(h.Div(
    h.H1(title),
    h.P(content),
))

func (*CompiledTemplate) Render

func (t *CompiledTemplate) Render(w io.Writer, values ...ParamValue) error

Render writes the template directly with parameter values.

func (*CompiledTemplate) With

func (t *CompiledTemplate) With(values ...ParamValue) Builder

With creates a Builder with parameter values bound for rendering.

type Param

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

Param is a placeholder for dynamic content in a parameterized template. Use with CompileParams to create templates with variable content.

func NewParam

func NewParam(name string) *Param

NewParam creates a named placeholder for dynamic content in CompileParams.

title := h.NewParam("title")
tmpl, err := h.CompileParams(h.Div(h.H1(title)))
if err != nil {
	// handle error
}
tmpl.Render(w, title.Value(h.Text("Hello")))

func (*Param) Build

func (p *Param) Build(w *Writer) error

Build signals to CompileParams that a parameter slot was encountered. When used outside CompileParams, it renders nothing.

func (*Param) Value

func (p *Param) Value(b Builder) ParamValue

Value binds a Builder to this parameter for rendering.

type ParamValue

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

ParamValue binds a value to a parameter for rendering.

type TagArg

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

TagArg is a marker interface for types that can be passed to tag functions. Valid types are: Attributes, Attribute, and Builder.

type Writer

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

Writer is a low-level streaming HTML writer that wraps an io.Writer. It tracks open tags and provides methods for writing HTML elements, attributes, and content. Attribute values are automatically HTML-escaped.

func NewWriter

func NewWriter(w io.Writer) *Writer

NewWriter creates a new Writer that wraps the provided io.Writer. The Writer tracks open tags and provides methods for writing HTML elements.

func (*Writer) Close

func (w *Writer) Close() error

Close closes all remaining open tags in reverse order (most recent first).

func (*Writer) CloseOneTag

func (w *Writer) CloseOneTag() error

CloseOneTag closes the most recently opened tag. Returns ErrUnknownTagToClose if no tags are open.

func (*Writer) CloseTag

func (w *Writer) CloseTag(name string) error

CloseTag closes the specified tag and all tags opened after it. Returns ErrUnknownTagToClose if no tags are open or the specified tag is not found.

func (*Writer) Doctype

func (w *Writer) Doctype() error

Doctype writes the HTML5 doctype declaration (<!DOCTYPE html>).

func (*Writer) OpenTag

func (w *Writer) OpenTag(name string, as Attributes) error

OpenTag writes an opening HTML tag with the given name and attributes. The tag is added to the stack of open tags and must be closed with CloseTag, CloseOneTag, or Close. Attribute values are automatically HTML-escaped.

func (*Writer) Raw

func (w *Writer) Raw(unsafeHtml string) error

Raw writes unescaped HTML content. Use with caution as this can introduce XSS vulnerabilities if the content is not properly sanitized. When indentation is enabled, tracks whether content ends with newline.

func (*Writer) SelfClosingTag

func (w *Writer) SelfClosingTag(name string, as Attributes) error

SelfClosingTag writes a self-closing HTML tag with the given name and attributes. For example, SelfClosingTag("br", nil) writes "<br/>".

func (*Writer) SetIndent

func (w *Writer) SetIndent(prefix string)

SetIndent sets the indentation prefix used for pretty-printing. When set to a non-empty string, each nested element will be indented by that prefix and newlines will be added after tags.

func (*Writer) SetMaxLineLength

func (w *Writer) SetMaxLineLength(maxLen int)

SetMaxLineLength sets the maximum line length before wrapping attributes to new lines. When set to 0 (default), attributes are never wrapped. When the combined tag + attributes would exceed this length, additional attributes are placed on new lines with extra indentation.

func (*Writer) Text

func (w *Writer) Text(txt string) error

Text writes HTML-escaped text content. When indentation is enabled, text is indented at the current content depth and followed by a newline.

Jump to

Keyboard shortcuts

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