Template Option missingkey Error Mode

template.Option("missingkey=error") turns missing map keys from silent <no value> output into Execute errors that name the exact key.

GoConfig Management

Code

gosnippet
25 lines
package main

import (
	"fmt"
	"strings"
	"text/template"
)

func main() {
	src := "status: {{.service}} region={{.region}} replicas={{.replicas}}"
	data := map[string]any{"service": "orders", "replicas": 4}

	// default mode: a missing map key renders "<no value>", no error
	loose := template.Must(template.New("status").Parse(src))
	var looseOut strings.Builder
	looseErr := loose.Execute(&looseOut, data)
	fmt.Printf("loose: %q err=%v\n", looseOut.String(), looseErr)

	// missingkey=error mode: a missing key fails Execute and names the key
	strict := template.Must(template.New("status").Parse(src))
	strict.Option("missingkey=error")
	var strictOut strings.Builder
	strictErr := strict.Execute(&strictOut, data)
	fmt.Printf("strict err: %v\n", strictErr)
}

Inside the snippet

Template Option missingkey Error Mode keeps everything in the function main.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Putting it to use

The signature doing the main work is func main()

Watch for labeled lines in the run — loose:, strict err: — when the file runs.

The core lines, annotated

src := "status: {{.service}} region={{.region}} replicas={{.replicas}}"

Interactive Tools for This Topic

FAQ

What does Template Option missingkey Error Mode print when run?
Running the file directly is enough — expect labeled output lines such as `loose:`, `strict err:`.