Search code examples
templatesgogo-templates

is there a way to list used variables?


Let's say I have a basic go text/template:

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

I want to get an array of the variables names used in the template, to be able to skip the execution if they are not available in the data I pass to execute, is it possible to do that somehow?

As my data is not a struct but a map, doing .var will always return something: if it doesn't exist, it will return an empty string when I would have hoped to get an error when executing the template.

So for the example from above, I would have liked to get:

[var var2]

Solution

  • Use a template func that returns an error if a value isn't set. Something like this:

    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
        },
    })
    

    Then in your template:

    {{require .Value}}
    

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