使用数组作为第二个参数,而不是模板本身。
package mainimport ( "html/template" "log" "os")func main() { t := template.Must(template.New("").Parse(`{{- range .}}{{.}}: echo "from {{.}}"{{end}}`)) t.Execute(os.Stdout, []string{"app1", "app2", "app3"}) f, err := os.Create("./myfile") if err != nil { log.Println("create file: ", err) return } err = t.Execute(f, []string{"app1", "app2", "app3"}) if err != nil { log.Print("execute: ", err) return } f.Close()}输出:
app1: echo "from app1"app2: echo "from app2"app3: echo "from app3"
而且的内容
myfile是
app1: echo "from app1"app2: echo "from app2"app3: echo "from app3"



