Documentation
¶
Overview ¶
Package render renders Go text/template expressions embedded in the string values of an already-decoded document, resolving them against the document itself (self-reference) and against caller-supplied data.
Only string values containing "{{" are selected for rendering, and each result is a string. These replacements do not reshape the document, but caller-supplied helpers can mutate exposed maps and slices, including adding or removing fields. A literal "{{" is written as {{ "{{" }}.
WithSkip excludes whole strings before parsing while keeping them readable. HasTemplates uses the same selection without executing or modifying the document.
Self-reference and evaluation order ¶
The document is exposed to its own templates under the self key (default "self"; see WithSelfKey), so a field can reference a sibling:
name: example
greeting: "hello {{ .self.name }}"
Fields may reference other templated fields. Value builds a dependency graph from the self-references and evaluates fields in dependency order, so each field observes the rendered value of everything it depends on. Each field is evaluated exactly once. If the references form a cycle, Value returns an error that is ErrReferenceCycle.
To decide render order, Value works out which parts of the document each template reads. A template that uses a value in full depends on that value and everything nested inside it, so all of those render first:
{{ .self.disks }} printing it
{{ toJson .self.disks }} passing it to a function or named template
{{ $d = .self.disks }} reassigning an existing variable
A variable declared with := is tracked through its later uses; for example, {{ $d := .self.disks }}{{ $d }} reads the disks value when $d is printed.
A template that only tests a value depends on that value alone, not on what is nested inside it:
{{ if .self.disks }} {{ with .self.disks }} {{ range .self.disks }}
{{ len .self.disks }} {{ not .self.disks }}
{{ if and .self.a .self.b }} (and/or when used only for truthiness)
Fields used inside an if, with or range body are tracked on their own, so a loop depends only on the fields it uses from each element:
disks:
- name: sda
label: "{{ range .self.disks }}{{ .name }} {{ end }}"
Here label depends on every disk's name, but not on any disk's label. If the loop body used {{ .label }} instead, label would depend on itself and Value would report a cycle. The same applies to {{ toJson .self.disks }}, which uses every field of every disk. The analysis errs on the side of caution, so it can report a cycle that would not actually occur when the template runs.
Caller data is merged into the same root, so templates may also reference external values (for example {{ .references.net.spec.domain }}). Data values are never themselves templated.
Resource limits ¶
Each field is rendered under an output-size cap (WithMaxOutputBytes, default 1 MiB) and a best-effort output-write deadline (WithOutputDeadline, default 2s), and the combined output of all fields is capped too (WithMaxTotalBytes, default 8 MiB). A breach is reported as a *FieldError that is ErrOutputTooLarge, ErrTotalOutputTooLarge or ErrOutputDeadline. The deadline applies per field and is checked only when output is written; it cannot interrupt a blocked function or execution that produces no output.
These limits are operational safeguards against mistakes, not a security boundary. They cap rendered output, not memory or CPU: a template can allocate or loop without writing, for example by growing a variable in a range. Only trusted authors should be able to supply templates.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrOutputDeadline = errors.New("render: output deadline exceeded")
ErrOutputDeadline is returned, wrapped in a *FieldError, when output is written after the deadline set by WithOutputDeadline.
var ErrOutputTooLarge = errors.New("render: output too large")
ErrOutputTooLarge is returned, wrapped in a *FieldError, when a field's rendered output exceeds the maximum size (see WithMaxOutputBytes).
var ErrReferenceCycle = errors.New("render: reference cycle")
ErrReferenceCycle is returned by Value when self-references between fields form a cycle, so no evaluation order exists. Use errors.As with *CycleError to inspect the fields involved.
var ErrTotalOutputTooLarge = errors.New("render: total output too large")
ErrTotalOutputTooLarge is returned, wrapped in a *FieldError, when the combined rendered output of all fields exceeds the maximum size (see WithMaxTotalBytes).
Functions ¶
func HasTemplates ¶
HasTemplates reports whether doc contains any non-skipped string values with template delimiters. It neither parses templates nor modifies doc.
func Value ¶
Value renders, in place, the templated string values of doc, a document decoded into map[string]any, []any and scalars, and returns it.
doc is exposed to its own templates under the self key and data is merged into the same root. It returns an error that is ErrReferenceCycle if fields reference each other in a cycle, and a *FieldError if a specific field fails to parse or execute. On error, doc may be partially rendered.
Example ¶
package main
import (
"fmt"
"github.com/tinkerbell/tinkerbell/pkg/template/render"
)
func main() {
doc := map[string]any{
"name": "machine1",
"fqdn": "{{ .self.name }}.{{ .references.net.domain }}",
}
data := map[string]any{"references": map[string]any{"net": map[string]any{"domain": "example.org"}}}
out, err := render.Value(doc, data)
if err != nil {
panic(err)
}
fmt.Println(out.(map[string]any)["fqdn"])
}
Output: machine1.example.org
Types ¶
type CycleError ¶
type CycleError struct {
// Fields is the cycle as a path, e.g. ["a", "b", "a"].
Fields []string
}
CycleError reports a reference cycle and the field paths involved, in the order they reference one another.
func (*CycleError) Error ¶
func (e *CycleError) Error() string
func (*CycleError) Is ¶
func (e *CycleError) Is(target error) bool
Is reports whether the target is ErrReferenceCycle.
type FieldError ¶
type FieldError struct {
// Path is the dotted/indexed location of the offending field.
Path string
// Err is the underlying parse or execution error.
Err error
}
FieldError annotates a template parse or execution failure with the path of the field that caused it, for example "spec.instance.hostname" or "spec.interfaces[0].dhcp.hostname".
func (*FieldError) Error ¶
func (e *FieldError) Error() string
func (*FieldError) Unwrap ¶
func (e *FieldError) Unwrap() error
type Option ¶
type Option func(*config)
Option configures a Value call.
func WithMaxOutputBytes ¶
WithMaxOutputBytes caps the rendered size of any single field. Exceeding it fails with an error that is ErrOutputTooLarge. The default is 1 MiB; 0 disables the cap.
func WithMaxTotalBytes ¶
WithMaxTotalBytes caps the combined rendered size of all fields in one Value call. Exceeding it fails with an error that is ErrTotalOutputTooLarge. The default is 8 MiB; 0 disables the cap.
func WithMissingKeyError ¶
WithMissingKeyError controls whether referencing a missing map key is an error (true, the default) or renders as "<no value>" (false). The index function is unaffected and returns no value for a missing key.
func WithOutputDeadline ¶
WithOutputDeadline sets a best-effort deadline checked whenever a field writes output. It does not interrupt template functions or execution that produces no output. The default is 2s; 0 disables the deadline.
func WithSelfKey ¶
WithSelfKey sets the root key under which the document is exposed to its own templates. The default is "self".