golang: iterating over map in text template

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 (

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}}
		{{range $Name, $Value := .Env -}}
		{{$Name}}: {{$Value}}

	templ, err := template.New("app").Parse(temp)
	if err != nil {

	err = templ.Execute(os.Stdout, app)
	if err != nil {

The character - on line 32 is important because this remove empty lines from generated text.


	name:	testapp
	cwd:	~/
		DEBUG: false
		PORT: 8000

Why this?

Because when i was looking for it i was getting only stupid not usable examples.

Publikováno v Go