To use the value of a map, you need to specify the name of the key of that field preceded by a period(.), such as .keyName.
package main
import (
"os"
"text/template"
)
func main() {
var err error
constants := map[string]int{
"value1": 3711,
"value2": 2138,
}
tmpl := `{
"text1": "lorem ipsum {{ .value1 }}/12"
"text2": "lorem ipsum {{ .value2 }}/24"
}`
t := template.New("hello")
tt, err := t.Parse(tmpl)
if err != nil {
panic(err)
}
if err = tt.Execute(os.Stdout, &constants); err != nil {
panic(err)
}
}
Output:
{
"text1": "lorem ipsum 3711/12"
"text2": "lorem ipsum 2138/24"
}
Go Playground
For more complex use-cases, you can take a look at this code.
{{value1}}is a function call. Use{{.value1}}to get thevalue1field of dot.