gomplate

package module
v4.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 50 Imported by: 0

README

Gomplate

Flanksource Gomplate is a fork of hairyhenderson/gomplate that provides a unified templating library supporting multiple expression languages.

Features

  • Go Text/Template – Full Go text/template support with an extended function library from gomplate (base64, collections, crypto, data formats, filepath, math, random, regexp, strings, time, and more)
  • CEL (Common Expression Language) – CEL support with:
    • Standard CEL operators and built-ins
    • cel-go extensions (strings, encoders, lists, math, sets)
    • Kubernetes-specific helpers (k8s.*)
    • AWS helpers (aws.*)
    • Many gomplate functions remapped into CEL (base64, math, random, regexp, filepath, crypto, sets, etc.)
    • Optional-type support (obj.?field.orValue("default"))
  • JavaScript (otto) – Lightweight JS evaluation via otto
  • Struct templating – Walk Go structs/maps and apply templates to string fields in-place

Quick Reference

Language Example Documentation
Go Template {{ .name | strings.ToUpper }} GO_TEMPLATE.md
CEL name.upperAscii() CEL.md
CEL Quick Reference
# Arithmetic
2 + 3           // 5
"hello" + " world"   // "hello world"
[1,2] + [3,4]   // [1,2,3,4]

# Comparison / Logic
x > 5 && y != null
true ? "yes" : "no"

# String methods
"hello world".upperAscii()        // "HELLO WORLD"
"hello world".split(" ")          // ["hello", "world"]
"hello".startsWith("he")          // true
"hello world".contains("world")   // true

# Collections
[1,2,3].filter(e, e > 1)          // [2, 3]
[1,2,3].map(e, e * 2)             // [2, 4, 6]
[1,2,3].all(e, e > 0)             // true
{"a":1,"b":2}.keys()              // ["a","b"]

# Optional / null-safety
obj.?field.orValue("default")
obj.?a.?b.orValue("fallback")

# Kubernetes
k8s.isHealthy(pod)
k8s.cpuAsMillicores("500m")       // 500
k8s.memoryAsBytes("1Gi")

# Math
math.Add([1,2,3])                 // 6
math.greatest([1,2,3])            // 3

# Time
time.Now()
time.Since(timestamp("2023-01-01T00:00:00Z"))

See CEL.md for full reference.

Go Template Quick Reference
# Variables and output
{{ .name }}
{{ $x := "hello" }}{{ $x | strings.ToUpper }}

# Control flow
{{ if eq .status "ok" }}OK{{ else }}FAIL{{ end }}
{{ range .items }}{{ . }}{{ end }}

# String functions
{{ "hello world" | strings.ToUpper }}        // HELLO WORLD
{{ "hello world" | strings.Split " " }}      // [hello world]
{{ "hello" | strings.Repeat 3 }}             // hellohellohello

# Data
{{ '{"key":"val"}' | json }}                 // map access
{{ .obj | toJSON }}
{{ .obj | toYAML }}

# Collections
{{ coll.Dict "a" 1 "b" 2 | toJSON }}         // {"a":1,"b":2}
{{ slice 1 2 3 | coll.Reverse | toJSON }}     // [3,2,1]
{{ coll.Sort (slice "b" "a" "c") | toJSON }}  // ["a","b","c"]

# Math
{{ math.Add 1 2 3 }}                          // 6
{{ math.Max 1 5 3 }}                          // 5

# base64
{{ base64.Encode "hello" }}                   // aGVsbG8=
{{ "aGVsbG8=" | base64.Decode }}              // hello

# Crypto
{{ crypto.SHA256 "hello" }}

# Delimiters (change if conflict with Helm)
# gotemplate: left-delim=$[[ right-delim=]]
$[[ .name ]]

See GO_TEMPLATE.md for full reference.

Installation

import "github.com/flanksource/gomplate/v4"

Usage

Go Template
result, err := gomplate.RunTemplate(map[string]any{
    "name": "world",
}, gomplate.Template{
    Template: `Hello, {{ .name }}!`,
})
CEL
result, err := gomplate.RunTemplate(map[string]any{
    "name": "world",
}, gomplate.Template{
    Expression: `"Hello, " + name + "!"`,
})
Struct Templating
type Config struct {
    Message string
    Count   int
}

cfg := Config{Message: "Hello, {{ .name }}!"}

err := gomplate.Walk(map[string]any{"name": "world"}, &cfg)
// cfg.Message == "Hello, world!"

## CEL eval helper

A small helper command is available at `cmd/ceval` to evaluate CEL expressions against an input YAML or JSON file.

Run it with:

```bash
go run ./cmd/ceval -f env.yaml -e "labels['a/b/c']"

Example input file:

labels:
  a/b/c: d

Output:

d

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CELKeywords

func CELKeywords() []string

CELKeywords returns the reserved words, sorted. Editor tooling needs the set itself, not just membership tests.

func CELValue

func CELValue(out ref.Val) any

CELValue unwraps CEL-created aggregates without converting numbers through JSON. Host-provided native objects retain their original type.

func CompileEnvOptions

func CompileEnvOptions(environment map[string]any, template Template) []cel.EnvOption

CompileEnvOptions returns the options RunExpressionContext will compile the template against: the static set plus the per-call variables, registered native types, Functions and CelEnvs.

For callers that want to compile an expression themselves before running it, to get a source position out of the issues -- which RunExpression's error does not carry. Building that environment from GetCelEnv alone reports a template's own Functions and CelEnvs as undeclared references.

func CreateFuncs

func CreateFuncs(ctx context.Context) template.FuncMap

CreateFuncs - function mappings are created here

func GetCelEnv

func GetCelEnv(environment map[string]any) []cel.EnvOption

GetCelEnv returns the full set of CEL env options: the static options, any types registered via RegisterType, and one variable per environment key.

RunExpressionContext no longer uses this on the hot path; it compiles against the cached base environment (baseCelEnv) and layers the per-call options with Env.Extend. GetCelEnv is retained for external callers and shares the static option set via staticCelEnvOptions.

func IsCelKeyword

func IsCelKeyword(key string) bool

IsCelKeyword returns true if the given key is a reserved word in Cel

func IsValidCELIdentifier

func IsValidCELIdentifier(s string) bool

func LoadSharedLibrary

func LoadSharedLibrary(source string) error

LoadSharedLibrary loads a shared library for Otto

func RegisterType

func RegisterType(value any) error

RegisterType makes a Go or CEL type available to subsequent CEL evaluations.

func RunExpression

func RunExpression(environment map[string]any, template Template) (any, error)

func RunExpressionContext

func RunExpressionContext(ctx commonsContext.Context, environment map[string]any, template Template) (any, error)

func RunTemplate

func RunTemplate(environment map[string]any, template Template) (string, error)

func RunTemplateBool

func RunTemplateBool(environment map[string]any, template Template) (bool, error)

func RunTemplateContext

func RunTemplateContext(ctx commonsContext.Context, environment map[string]any, template Template) (string, error)

func Serialize

func Serialize(in map[string]any) (out map[string]any, err error)

Serialize iterates over each key-value pair in the input map and serializes any struct value to map[string]any, for Go templates. CEL reads the environment lazily (celInput).

func WithCELTracker

func WithCELTracker(ctx commonsContext.Context, tracker *CELTracker) commonsContext.Context

WithCELTracker enables native CEL state tracking for evaluations using ctx.

Types

type AsMapper

type AsMapper = celvalues.AsMapper

type CELTraceSnapshot

type CELTraceSnapshot struct {
	AST     *cel.Ast
	Details *cel.EvalDetails
	Output  ref.Val
}

CELTraceSnapshot exposes cel-go's native syntax and evaluation state for one completed evaluation. It is empty when compilation fails.

type CELTracker

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

CELTracker captures native CEL evaluation state when attached to a context. A tracker may be reused sequentially, but not concurrently.

func NewCELTracker

func NewCELTracker() *CELTracker

NewCELTracker creates an opt-in native CEL evaluation tracker.

func (*CELTracker) Snapshot

func (t *CELTracker) Snapshot() CELTraceSnapshot

type CelFunction

type CelFunction struct {
	Name      string
	Overloads []CelOverload
	// Impl serves every overload; overloadID names the one that matched the call.
	Impl cel.LateBoundFunction
}

CelFunction declares a CEL function whose implementation is supplied on each evaluation, so the compiled environment and program can be cached while Impl closes over per-call state (a request context, a database handle, ...).

type CelOverload

type CelOverload struct {
	ID     string
	Member bool
	Args   []*cel.Type
	Result *cel.Type
}

CelOverload is one signature of a CelFunction. Member declares a receiver-style overload, whose receiver is Args[0].

type DefaultValuesProvider

type DefaultValuesProvider struct{}

DefaultValuesProvider exposes a go template environment without serializing it up front: struct fields are read by their encoding/json key as the template reaches them, and only the values a template prints, ranges over, tests or passes to a function are serialized, exactly as Serialize would have converted them.

func (DefaultValuesProvider) Field

func (DefaultValuesProvider) Field(receiver reflect.Value, name string) (reflect.Value, bool, error)

func (DefaultValuesProvider) Value

type Delims

type Delims struct {
	Left, Right string
}

type MetricsType

type MetricsType struct {
	// times for rendering each template
	RenderDuration map[string]time.Duration
	// time it took to gather templates
	GatherDuration time.Duration
	// time it took to render all templates
	TotalRenderDuration time.Duration

	TemplatesGathered  int
	TemplatesProcessed int
	Errors             int
}

MetricsType - Warning: experimental! This may change in breaking ways without warning. This is not subject to any semantic versioning guarantees!

var Metrics *MetricsType

Metrics tracks interesting basic metrics around gomplate executions. Warning: experimental! This may change in breaking ways without warning. This is not subject to any semantic versioning guarantees!

type StructTemplater

type StructTemplater struct {
	Context context.Context
	Values  map[string]interface{}
	// IgnoreFields from walking where key is field name and value is field type
	IgnoreFields map[string]string
	Funcs        map[string]any
	DelimSets    []Delims
	// If specified create a function for each value so that is can be accessed via {{ value }} in addition to {{ .value }}
	ValueFunctions bool
	RequiredTag    string
}

func (StructTemplater) Struct

func (w StructTemplater) Struct(reflect.Value) error

this func is required to fulfil the reflectwalk.StructWalker interface

func (StructTemplater) StructField

func (w StructTemplater) StructField(f reflect.StructField, v reflect.Value) error

func (StructTemplater) Template

func (w StructTemplater) Template(val string) (string, error)

func (StructTemplater) Walk

func (w StructTemplater) Walk(object interface{}) error

type Template

type Template struct {
	Template   string `yaml:"template,omitempty" json:"template,omitempty"` // Go template
	JSONPath   string `yaml:"jsonPath,omitempty" json:"jsonPath,omitempty"`
	Expression string `yaml:"expr,omitempty" json:"expr,omitempty"` // A cel-go expression
	Javascript string `yaml:"javascript,omitempty" json:"javascript,omitempty"`
	RightDelim string `yaml:"-" json:"-"`
	LeftDelim  string `yaml:"-" json:"-"`

	// DelimSets, when non-empty, runs the gotemplate over the input once per
	// delimiter pair, feeding the output of each pass into the next. Useful for
	// inputs that mix delimiter styles (e.g. {{ }} and $( )).
	// A header (# gotemplate: left-delim=… right-delim=…) overrides DelimSets to
	// a single pass. Falls back to LeftDelim/RightDelim if both are set, otherwise
	// to the default {{ }}.
	DelimSets []Delims `yaml:"-" json:"-"`

	// ValueFunctions, when true, exposes each key in the environment as a
	// zero-arg function in addition to dot-access. Enables {{ foo }} alongside
	// the standard {{ .foo }}.
	ValueFunctions bool `yaml:"-" json:"-"`

	// Strict disables nil-safe evaluation: for cel expressions missing attributes are errors, and
	// for go templates field access through nil and out-of-range or nil index are errors.
	Strict bool `yaml:"-" json:"-"`

	// ValuesProvider resolves fields and shapes consumed values for go templates, so the
	// environment is read lazily instead of being serialized up front.
	// Nil uses DefaultValuesProvider.
	ValuesProvider gotemplate.ValuesProvider `yaml:"-" json:"-"`

	// CelEnvs are additional, opaque cel-env options. A template with CelEnvs is
	// never cached: its compiled program could hold a binding that closes over
	// an earlier call's state. Declare context-bound functions as CelFunctions.
	CelEnvs []cel.EnvOption `yaml:"-" json:"-"`

	// CelFunctions are CEL functions whose implementations are bound on each
	// evaluation, so templates using them are still cached by their declarations.
	CelFunctions []CelFunction `yaml:"-" json:"-"`

	// A map of functions that are accessible to cel expressions
	// and go templates.
	// NOTE: For cel expressions, the functions must be of type func() any.
	// If any other function type is used, an error will be returned.
	// Opt to CelFunctions for those cases.
	Functions map[string]any `yaml:"-" json:"-"`

	// CacheKey, when non-empty, is used as the program-cache key for this
	// template, bypassing the IsCacheable() heuristic. The caller asserts that
	// any two templates sharing this key may share the compiled cel.Program
	// (same expression semantics, same env shape, same function semantics).
	//
	// NOTE: CacheKey applies to cel expressions only. The go template path ignores
	// it and always derives its key from the template body and delimiters. A parsed
	// go template keeps the Functions it was parsed with, and the caller cannot
	// assert those are interchangeable across calls; see isGoTemplateCacheable.
	CacheKey string `yaml:"-" json:"-"`

	// CacheTime controls how long the compiled program/template is retained
	// in the cache. Zero means use the cache's default TTL; a positive value
	// is an explicit TTL; a negative value means no expiration.
	CacheTime time.Duration `yaml:"-" json:"-"`
}

func (Template) IsCacheable

func (t Template) IsCacheable() bool

func (Template) IsEmpty

func (t Template) IsEmpty() bool

func (Template) ShortString

func (t Template) ShortString() string

func (Template) String

func (t Template) String() string

Directories

Path Synopsis
Package base64 contains Base64 encoding/decoding functions
Package base64 contains Base64 encoding/decoding functions
Package celext copies cel-go's Strings, Encoders, Lists, Math, and Sets extension libraries.
Package celext copies cel-go's Strings, Encoders, Lists, Math, and Sets extension libraries.
internal/sync command
Command sync copies the selected cel-go extensions and applies the cost-model opt-out.
Command sync copies the selected cel-go extensions and applies the cost-model opt-out.
Package celvalues provides civil dates and Commons Money integration for CEL.
Package celvalues provides civil dates and Commons Money integration for CEL.
cmd
ceval command
genmonarch command
Command genmonarch generates the Monaco language definitions for the expression languages gomplate evaluates.
Command genmonarch generates the Monaco language definitions for the expression languages gomplate evaluates.
playground command
Command playground serves the evaluation API behind the language playground.
Command playground serves the evaluation API behind the language playground.
Package coll contains functions to help manipulate and query collections of data, like slices/arrays and maps.
Package coll contains functions to help manipulate and query collections of data, like slices/arrays and maps.
Package conv contains functions that help converting data between different types
Package conv contains functions that help converting data between different types
Package data contains functions that parse and produce data structures in different formats.
Package data contains functions that parse and produce data structures in different formats.
Package funcs is an internal package that provides gomplate namespaces and functions to be used in 'text/template' templates.
Package funcs is an internal package that provides gomplate namespaces and functions to be used in 'text/template' templates.
Package genmonarch builds Monaco language definitions for the expression languages gomplate runs, from the grammars and registries gomplate itself uses -- so the editor cannot drift from the evaluator.
Package genmonarch builds Monaco language definitions for the expression languages gomplate runs, from the grammars and registries gomplate itself uses -- so the editor cannot drift from the evaluator.
grammar
Package grammar extracts lexical vocabulary from the grammars of the parsers gomplate actually runs, so the editor tokenizers stay in step with them instead of being transcribed by hand.
Package grammar extracts lexical vocabulary from the grammars of the parsers gomplate actually runs, so the editor tokenizers stay in step with them instead of being transcribed by hand.
hack
hostplayground command
Command hostplayground stands in for a host like mission-control: it serves the playground API with a function of its own registered through playground.Options, so the whole path -- catalogue, highlighting, completion, hover, evaluation -- can be exercised the way a host will exercise it.
Command hostplayground stands in for a host like mission-control: it serves the playground API with a function of its own registered through playground.Options, so the whole path -- catalogue, highlighting, completion, hover, evaluation -- can be exercised the way a host will exercise it.
internal
Package math contains set of basic math functions to be able to perform simple arithmetic operations
Package math contains set of basic math functions to be able to perform simple arithmetic operations
Package playground evaluates expressions for the language playground, using the same entry points a gomplate caller uses so what the playground shows is what production does.
Package playground evaluates expressions for the language playground, using the same entry points a gomplate caller uses so what the playground shows is what production does.
Package random contains functions for generating random values
Package random contains functions for generating random values
Package regexp contains functions for dealing with regular expressions
Package regexp contains functions for dealing with regular expressions
Package duration contains routines to parse standard units of time.
Package duration contains routines to parse standard units of time.
Package test contains functions to help validate assumptions and can cause template generation to fail in specific cases
Package test contains functions to help validate assumptions and can cause template generation to fail in specific cases
Package template implements data-driven templates for generating textual output.
Package template implements data-driven templates for generating textual output.
internal/fmtsort
Package fmtsort provides a general stable ordering mechanism for maps, on behalf of the fmt and text/template packages.
Package fmtsort provides a general stable ordering mechanism for maps, on behalf of the fmt and text/template packages.
Package time contains functions to help work with date and time
Package time contains functions to help work with date and time
Package tmpl contains functions for defining or executing in-line templates.
Package tmpl contains functions for defining or executing in-line templates.

Jump to

Keyboard shortcuts

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