Documentation
¶
Overview ¶
Package h provides a low-level streaming HTML writer and a declarative builder API for programmatic HTML generation.
Index ¶
- Variables
- func Render(w io.Writer, b Builder) error
- func RenderBytes(b Builder) []byte
- func RenderIndent(w io.Writer, indent string, b Builder) error
- func RenderString(b Builder) string
- type Attribute
- type Attributes
- type Builder
- func A(args ...TagArg) Builder
- func Abbr(args ...TagArg) Builder
- func Address(args ...TagArg) Builder
- func Area(args ...TagArg) Builder
- func Article(args ...TagArg) Builder
- func Aside(args ...TagArg) Builder
- func Audio(args ...TagArg) Builder
- func B(args ...TagArg) Builder
- func Base(args ...TagArg) Builder
- func Bdi(args ...TagArg) Builder
- func Bdo(args ...TagArg) Builder
- func Blockquote(args ...TagArg) Builder
- func Body(args ...TagArg) Builder
- func Br(args ...TagArg) Builder
- func Button(args ...TagArg) Builder
- func Canvas(args ...TagArg) Builder
- func Caption(args ...TagArg) Builder
- func Cite(args ...TagArg) Builder
- func Code(args ...TagArg) Builder
- func Col(args ...TagArg) Builder
- func Colgroup(args ...TagArg) Builder
- func Compile(b Builder) (Builder, error)
- func CustomElement(name string, args ...TagArg) Builder
- func Data(args ...TagArg) Builder
- func Datalist(args ...TagArg) Builder
- func Dd(args ...TagArg) Builder
- func Del(args ...TagArg) Builder
- func Details(args ...TagArg) Builder
- func Dfn(args ...TagArg) Builder
- func Dialog(args ...TagArg) Builder
- func Div(args ...TagArg) Builder
- func Dl(args ...TagArg) Builder
- func Dt(args ...TagArg) Builder
- func Em(args ...TagArg) Builder
- func Embed(args ...TagArg) Builder
- func Fieldset(args ...TagArg) Builder
- func Figcaption(args ...TagArg) Builder
- func Figure(args ...TagArg) Builder
- func First(b ...Builder) Builder
- func Footer(args ...TagArg) Builder
- func ForEach[X any](s iter.Seq[X], fn func(X) Builder) Builder
- func ForEach2[X, Y any](s iter.Seq2[X, Y], fn func(X, Y) Builder) Builder
- func Form(args ...TagArg) Builder
- func Fragment(children ...Builder) Builder
- func H1(args ...TagArg) Builder
- func H2(args ...TagArg) Builder
- func H3(args ...TagArg) Builder
- func H4(args ...TagArg) Builder
- func H5(args ...TagArg) Builder
- func H6(args ...TagArg) Builder
- func Head(args ...TagArg) Builder
- func Header(args ...TagArg) Builder
- func Hgroup(args ...TagArg) Builder
- func Hr(args ...TagArg) Builder
- func Html(args ...TagArg) Builder
- func I(args ...TagArg) Builder
- func If(cond bool, ifTrue, ifElse Builder) Builder
- func Iframe(args ...TagArg) Builder
- func Img(args ...TagArg) Builder
- func Input(args ...TagArg) Builder
- func Ins(args ...TagArg) Builder
- func Kbd(args ...TagArg) Builder
- func Label(args ...TagArg) Builder
- func Legend(args ...TagArg) Builder
- func Li(args ...TagArg) Builder
- func Link(args ...TagArg) Builder
- func Main(args ...TagArg) Builder
- func Map(args ...TagArg) Builder
- func Mark(args ...TagArg) Builder
- func Math(args ...TagArg) Builder
- func Menu(args ...TagArg) Builder
- func Meta(args ...TagArg) Builder
- func Meter(args ...TagArg) Builder
- func MustCompile(b Builder) Builder
- func Nav(args ...TagArg) Builder
- func Noscript(args ...TagArg) Builder
- func Object(args ...TagArg) Builder
- func Ol(args ...TagArg) Builder
- func Optgroup(args ...TagArg) Builder
- func Option(args ...TagArg) Builder
- func Output(args ...TagArg) Builder
- func P(args ...TagArg) Builder
- func Picture(args ...TagArg) Builder
- func Portal(args ...TagArg) Builder
- func Pre(args ...TagArg) Builder
- func Progress(args ...TagArg) Builder
- func Q(args ...TagArg) Builder
- func Raw(value string) Builder
- func Rp(args ...TagArg) Builder
- func Rt(args ...TagArg) Builder
- func Ruby(args ...TagArg) Builder
- func S(args ...TagArg) Builder
- func Samp(args ...TagArg) Builder
- func Script(args ...TagArg) Builder
- func Search(args ...TagArg) Builder
- func Section(args ...TagArg) Builder
- func Select(args ...TagArg) Builder
- func Slot(args ...TagArg) Builder
- func Small(args ...TagArg) Builder
- func Source(args ...TagArg) Builder
- func Span(args ...TagArg) Builder
- func Strong(args ...TagArg) Builder
- func Style(args ...TagArg) Builder
- func Sub(args ...TagArg) Builder
- func Summary(args ...TagArg) Builder
- func Sup(args ...TagArg) Builder
- func Svg(args ...TagArg) Builder
- func Table(args ...TagArg) Builder
- func Tbody(args ...TagArg) Builder
- func Td(args ...TagArg) Builder
- func Template(args ...TagArg) Builder
- func Text(value string) Builder
- func Textarea(args ...TagArg) Builder
- func Textf(format string, args ...any) Builder
- func Tfoot(args ...TagArg) Builder
- func Th(args ...TagArg) Builder
- func Thead(args ...TagArg) Builder
- func Time(args ...TagArg) Builder
- func Title(args ...TagArg) Builder
- func Tr(args ...TagArg) Builder
- func Track(args ...TagArg) Builder
- func U(args ...TagArg) Builder
- func Ul(args ...TagArg) Builder
- func Unless(cond bool, ifFalse Builder) Builder
- func Var(args ...TagArg) Builder
- func Video(args ...TagArg) Builder
- func Wbr(args ...TagArg) Builder
- func When(cond bool, ifTrue Builder) Builder
- type CompiledTemplate
- type Param
- type ParamValue
- type TagArg
- type Writer
- func (w *Writer) Close() error
- func (w *Writer) CloseOneTag() error
- func (w *Writer) CloseTag(name string) error
- func (w *Writer) Doctype() error
- func (w *Writer) OpenTag(name string, as Attributes) error
- func (w *Writer) Raw(unsafeHtml string) error
- func (w *Writer) SelfClosingTag(name string, as Attributes) error
- func (w *Writer) SetIndent(prefix string)
- func (w *Writer) SetMaxLineLength(maxLen int)
- func (w *Writer) Text(txt string) error
Constants ¶
This section is empty.
Variables ¶
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 ¶
Render writes the HTML representation of the given Builder to w. Returns nil if b is nil.
func RenderBytes ¶
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 ¶
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 ¶
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 ¶
Attribute represents a single HTML attribute as a name-value pair.
func AttrIf ¶
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 ¶
Builder is the interface implemented by all HTML node builders. Implementations write their HTML representation to the provided Writer.
func Blockquote ¶
Blockquote creates a <blockquote> element for extended quotations.
func Compile ¶
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 ¶
CustomElement creates a custom HTML element with the given tag name.
func Figcaption ¶
Figcaption creates a <figcaption> element for figure captions.
func First ¶
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 ForEach ¶
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 ¶
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 Html ¶
Html creates the root <html> element with DOCTYPE declaration. Sets lang="en" by default if not specified in attributes.
func If ¶
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 MustCompile ¶
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 Raw ¶
Raw creates a Builder that renders unescaped HTML content. Use with caution as this can introduce XSS vulnerabilities.
func Textf ¶
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 Unless ¶
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)"))),
)
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 ¶
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 ¶
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 ¶
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) CloseOneTag ¶
CloseOneTag closes the most recently opened tag. Returns ErrUnknownTagToClose if no tags are open.
func (*Writer) CloseTag ¶
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) 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 ¶
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 ¶
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 ¶
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.