render

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package render is part of the GoFastr framework. See https://github.com/DonaldMurillo/gofastr for documentation.

Package render provides a type-safe HTML template engine built from scratch. Templates are Go code producing HTML with compile-time type checking and auto-escaping. Inspired by Templ.

All text content is HTML-escaped by default. Use Raw for trusted markup.

Index

Constants

This section is empty.

Variables

View Source
var FuncMap = map[string]any{
	"ToUpper":      strings.ToUpper,
	"ToLower":      strings.ToLower,
	"Trim":         strings.TrimSpace,
	"Title":        strings.Title,
	"DateFormat":   func(t time.Time, layout string) string { return t.Format(layout) },
	"NumberFormat": func(n float64, prec int) string { return strconv.FormatFloat(n, 'f', prec, 64) },
	"Truncate": func(s string, maxRunes int) string {
		if utf8.RuneCountInString(s) <= maxRunes {
			return s
		}
		runes := []rune(s)
		return string(runes[:maxRunes]) + "…"
	},
}

FuncMap is the default set of template functions available for use in rendering pipelines. Call RegisterFunc to add custom functions.

Functions

func Attr

func Attr(key, value string) string

Attr formats a single HTML attribute as key="value" with the value HTML-escaped.

The key is validated against a strict allow-list (ASCII letters, digits, `-`, `_`, `:`). Keys containing whitespace would let a caller smuggle a second attribute — e.g. `src onerror` becomes a fresh `onerror=` attribute when concatenated into a tag. Keys beginning with `on` (case-insensitive) are inline event handlers and are never legitimately constructed via this builder — a host that needs one should be writing handlers in runtime.js, not injecting JS into the HTML. Both cases return the empty string so the attribute is dropped from any tag that includes it.

func ClassIf

func ClassIf(cond bool, name string) string

ClassIf returns name when cond is true, otherwise the empty string. Argument order matches Go's `if cond { name }` reading order. Designed for use inside Classes:

render.Classes("base", render.ClassIf(isActive, "active"))

func Classes

func Classes(parts ...string) string

Classes joins non-empty string args with spaces. Pair with ClassIf for conditional class lists:

class := render.Classes(
    "p-cond-row",
    render.ClassIf(active, "active"),
    render.ClassIf(hasError, "error"),
)

The returned string is plain text and is HTML-escaped automatically when assigned to a tag attribute via Tag or any html.* config.

For wide predicate-driven sets, see html.Classes(map[string]bool).

func Escape

func Escape(s string) string

Escape replaces the five special HTML characters with their entity equivalents: &, <, >, ", '. This prevents XSS when inserting untrusted data into HTML documents.

func GetComponent

func GetComponent(name string) (any, bool)

GetComponent retrieves a previously registered component by name. Returns the function value and true if found, or nil and false. The caller should type-assert the result to the expected func signature.

func HTMLHandler

func HTMLHandler(fn func(r *http.Request) HTML) http.HandlerFunc

HTMLHandler adapts a function that returns HTML into an http.HandlerFunc. This is the primary way to connect GoFastr templates to the Router.

func RegisterComponent

func RegisterComponent(name string, fn any)

RegisterComponent registers a component function under the given name. The function must have the signature func(T) HTML for some concrete type T. It panics if fn is nil.

func RegisterFunc

func RegisterFunc(name string, fn any)

RegisterFunc adds a named function to the global FuncMap. It panics if fn is nil or a function is already registered under name.

func RegisterLayout

func RegisterLayout(name string, layout Layout)

RegisterLayout registers a Layout under the given name for later retrieval via RenderWithLayout.

func RespondHTML

func RespondHTML(w http.ResponseWriter, h HTML)

RespondHTML writes the given HTML to the response with the correct Content-Type header and a 200 OK status.

Types

type Component

type Component[T any] func(data T) HTML

Component is a reusable template function parameterised by data of type T. Any function matching func(T) HTML can be used as a Component.

type HTML

type HTML string

HTML is a type-safe wrapper around an HTML string fragment. Values of type HTML are assumed to contain safe, well-formed markup. Construct HTML values using Tag, Text, Raw, VoidTag, and Join.

func If

func If(cond bool, html HTML) HTML

If returns html when cond is true, otherwise an empty fragment. Useful for inline conditional rendering:

Tag("div", nil,
    Text("hello"),
    If(user.Admin, adminBadge()),
)

Both arguments evaluate eagerly — Go has no lazy semantics here. When the truthy branch is expensive (database query, heavy allocation), use When instead so the function only runs when cond is true.

func Join

func Join(children ...HTML) HTML

Join concatenates zero or more HTML fragments into a single HTML value.

func Raw

func Raw(s string) HTML

Raw wraps the given string as HTML without any escaping. Only use Raw when the content is known to be safe, e.g. markup produced by trusted builder calls.

func RenderWithLayout

func RenderWithLayout(layoutName, title string, content HTML) HTML

RenderWithLayout looks up a registered Layout by name and applies it to the given title and content. Panics if no layout is registered under the given name.

func Tag

func Tag(name string, attrs map[string]string, children ...HTML) HTML

Tag builds an HTML element from a tag name, optional attributes, and zero or more child HTML fragments.

Tag("div", nil, Text("hello"))  →  <div>hello</div>
Tag("a", map[string]string{"href": "/"}, Text("home"))  →  <a href="/">home</a>

The tag name is validated against a strict allow-list (ASCII letters, digits and `-`). A name containing whitespace or other characters would otherwise let a caller smuggle attributes — e.g. a name of `div onclick="alert(1)"` would render as `<div onclick="alert(1)">` — so any invalid name is replaced with a neutral `span`.

func Text

func Text(s string) HTML

Text wraps the given string as auto-escaped HTML text content. The input is HTML-escaped to prevent injection of raw markup.

func VoidTag

func VoidTag(name string, attrs map[string]string) HTML

VoidTag builds a self-closing HTML element (e.g. <img>, <br>, <hr>, <input>, <meta>, <link>). The tag is rendered without a closing tag. The tag name is validated like Tag — see that doc for rationale.

func When

func When(cond bool, fn func() HTML) HTML

When returns fn() when cond is true, otherwise an empty fragment. Lazy variant of If that avoids constructing html when cond is false — preferred when the truthy branch is expensive.

func (HTML) String

func (h HTML) String() string

String returns the underlying HTML string.

type Layout

type Layout func(title string, content HTML) HTML

Layout is a function that wraps page content with a common chrome (head, navigation, footer, etc.). The title parameter allows the page to specify its own <title>.

Jump to

Keyboard shortcuts

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