How to use golang template missingkey parameter?

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 there is no key '/ foo / bar' on the map 'd', but everything is just fine. Did I miss something?

Here is the site: http://play.golang.org/p/Oqg1Dy4h1k

+4
source share
1 answer

The parameter missingkeydoes not work with index. You will get only the desired result when accessing the map with .<field-name>:

t, err := template.New("t1").Option("missingkey=error").Parse(`{{.foo}}`)
err = t.Execute(os.Stdout, d)

You can work around this by specifying your own index function, which returns an error when the 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_

+2
source

All Articles