Is there a way to list the variables used?

Say I have go body text / template:

{{.var}} is another {{.var2}}

I want to get an array of variable names used in a template to skip execution if they are not available in the data that I pass for execution, is this possible somehow?

Since my data is not a structure, but a map, executing .var will always return something: if it does not exist, it will return an empty string when I would hope to get an error while executing the template.

So, for the example above, I would like to get:

[var var2]
+4
source share
1 answer

Use the func function, which returns an error if no value is given. Something like that:

template.FuncMap(map[string]interface{}{
    "require": func(val interface{}) (interface{}, error) {
        if val == nil {
            return nil, errors.New("Required value not set.")
        }
        return val, nil
    },
}))

:

{{require .Value}}

http://play.golang.org/p/qZMBID7Y8L

+2

All Articles