Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use golang template missingkey option?

Tags:

go

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

like image 702
user5976738 Avatar asked Oct 31 '22 08:10

user5976738


1 Answers

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

like image 199
Tim Cooper Avatar answered Nov 12 '22 16:11

Tim Cooper