The missingkey
option does not work with index
. You will only get the desired result when you access the map using .<field-name>
:
t, err := template.New("t1").Option("missingkey=error").Parse(`{{.foo}}`)
err = t.Execute(os.Stdout, d)
You can get around this by defining your own index function that returns an error when a key is missing:
package main
import (
"errors"
"fmt"
"os"
"text/template"
)
func lookup(m map[string]interface{}, key string) (interface{}, error) {
val, ok := m[key]
if !ok {
return nil, errors.New("missing key " + key)
}
return val, nil
}
func main() {
d := map[string]interface{}{
"/foo/bar": 34,
}
fns := template.FuncMap{
"lookup": lookup,
}
t, err := template.New("t1").Funcs(fns).Parse(`{{ lookup . "/foo/baz" }}`)
if err != nil {
fmt.Println("ERROR 1")
}
err = t.Execute(os.Stdout, d)
if err != nil {
fmt.Println("ERROR 2")
}
}
https://play.golang.org/p/L12lFnJig_