I would expect
t, err := template.New("t1").Option("missingkey=error").Parse("{{index . \"/foo/bar\"}}")
err = t.Execute(os.Stdout, d)
to return an error if the map 'd' doesn't have a key '/foo/bar', but everything is just fine. Am I missing something?
Here's the go playground: http://play.golang.org/p/Oqg1Dy4h1k
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.Printf("ERROR 1: %q\n", err)
}
err = t.Execute(os.Stdout, d)
if err != nil {
fmt.Printf("ERROR 2: %q\n", err)
}
}
https://play.golang.org/p/0_ZZ2Pwa1uZ
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With