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]
Since a list can contain any Python variables, it can even contain other lists.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With