If You have map
with key and value in variable and you need iterate on it… Easy example for composing env variables in text template:
package main
import (
"log"
"os"
"text/template"
)
type env map[string]interface{}
type myapp struct {
Name string
CWD string
Env env
}
func main() {
app := myapp{
Name: "testapp",
CWD: "~/",
Env: env{
"PORT": 8000,
"DEBUG": false,
},
}
temp := `app:
name: {{.Name}}
cwd: {{.CWD}}
env:
{{range $Name, $Value := .Env -}}
{{$Name}}: {{$Value}}
{{end}}
`
templ, err := template.New("app").Parse(temp)
if err != nil {
log.Fatal(err)
}
err = templ.Execute(os.Stdout, app)
if err != nil {
log.Fatal(err)
}
}
The character -
on line 32 is important because this remove empty lines from generated text.
Output
app:
name: testapp
cwd: ~/
env:
DEBUG: false
PORT: 8000
Why this?
Because when i was looking for it i was getting only stupid not usable examples.