In Go I have a map[string]int
. I want to display values from this map through a Template from the text/template
package. If the map doesn't contain a specific value, I want to display "n/a" instead. This is what I have tried:
{{with index $.MyMap .MyKey}}{{.}}{{else}}n/a{{end}}
Unfortunately this doesn't work if the map contains a value for my key, but the value is 0. Then "n/a" is also displayed. How can I make sure that "n/a" is only displayed, if the map didn't contain the requested value?
You can create a template function, which returns n/a if key does not exist.
funcMap := template.FuncMap{
"GetValue": func(m map[string]int, key string) string {
if value, ok := m[key]; ok {
return fmt.Sprintf("%d", value)
}
return "n/a"
},
}
In you template you can call GetValue function. For example -
tmpl := `{{- $key1 := "one" -}}
{{- $key2 := "four" -}}
Value for '{{ $key1 }}': {{ GetValue . $key1 }} \n
Value for '{{ $key2 }}': {{ GetValue . $key2 }}`
Output is
Value for 'one': 1 /n
Value for 'four': n/a