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 ¶
- Variables
- func Attr(key, value string) string
- func ClassIf(cond bool, name string) string
- func Classes(parts ...string) string
- func Escape(s string) string
- func GetComponent(name string) (any, bool)
- func HTMLHandler(fn func(r *http.Request) HTML) http.HandlerFunc
- func RegisterComponent(name string, fn any)
- func RegisterFunc(name string, fn any)
- func RegisterLayout(name string, layout Layout)
- func RespondHTML(w http.ResponseWriter, h HTML)
- type Component
- type HTML
- func If(cond bool, html HTML) HTML
- func Join(children ...HTML) HTML
- func Raw(s string) HTML
- func RenderWithLayout(layoutName, title string, content HTML) HTML
- func Tag(name string, attrs map[string]string, children ...HTML) HTML
- func Text(s string) HTML
- func VoidTag(name string, attrs map[string]string) HTML
- func When(cond bool, fn func() HTML) HTML
- type Layout
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ¶
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 ¶
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 ¶
Escape replaces the five special HTML characters with their entity equivalents: &, <, >, ", '. This prevents XSS when inserting untrusted data into HTML documents.
func GetComponent ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 Raw ¶
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 ¶
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 ¶
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 ¶
Text wraps the given string as auto-escaped HTML text content. The input is HTML-escaped to prevent injection of raw markup.
func VoidTag ¶
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.