Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 912
Julien Fouilhé Avatar asked Feb 17 '15 00:02

Julien Fouilhé


People also ask

Can you list variables in Python?

Since a list can contain any Python variables, it can even contain other lists.

Can we store variable in list?

Storing Variables in ListsIt is also possible for a list to contain different types within it as well. Suppose you wanted to add the names of your parents and sisters to the list so you know which heights belong to whom. You can throw in some strings without issue.

What is __ name __ in Python?

The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script. Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.


1 Answers

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

like image 190
Trevor Dixon Avatar answered Sep 28 '22 09:09

Trevor Dixon