How to Use Template Conditionals and Loops in Go

Web
Use if and range directives in Go templates to handle conditionals and loops.

Go templates do not support conditionals or loops; use the html/template or text/template packages with if, range, and else directives in your template files.

package main

import (
	"os"
	"text/template"
)

func main() {
	tmpl := `{{if .}}Hello{{else}}Goodbye{{end}} {{range .}}- {{.}}{{end}}`
	t := template.Must(template.New("example").Parse(tmpl))
	t.Execute(os.Stdout, []string{"A", "B"})
}