用于源和目标打印的Golang模板
问题描述:
I want to generate go template with loop which looks like following
target1:
echo from target2
target2:
echo from target2
targetN:
echo from targetN
This simply creates a target and line after it prints from which target it's called.
I've tried with the following which works partially, any Idea what I miss here ? or how can I simplify the code in t.Execute
https://play.golang.org/p/iLWQANobKUL
package main
import (
"bytes"
"fmt"
"html/template"
)
func main() {
t := template.Must(template.New("").Parse(` {{- range .}} {{.Name}}:{{end}}
{{- range .}}
{{.Name}}:
{{"\t"}}echo from {{.Name}} {{.Text}}
{{end}}
`))
var buf bytes.Buffer
t.Execute(&buf, []interface{}{map[string]string{"Name": "target1", "Text": "echo"}})
fmt.Printf("%q
", buf.String())
}
答
Is this what you need?
package main
import (
"text/template"
"os"
)
func main() {
t := template.Must(template.New("").Parse(`{{- range .}}{{.}}:
echo from {{.}}
{{end}}
`))
t.Execute(os.Stdout, []string{"target1", "target2", "target3"})
}
Output:
target1:
echo from target1
target2:
echo from target2
target3:
echo from target3
Ref: https://golang.org/pkg/text/template/
Update:
If you want to use the pipeline as a map and want to use value from the value of the corresponding key, then:
package main
import (
"text/template"
"os"
)
func main() {
t := template.Must(template.New("").Parse(`{{- range $key, $val := .}}{{$key}}:
echo from {{$val}}
{{end -}}
`))
t.Execute(os.Stdout, map[string]string{"target1": "foo1", "target2": "bar2", "target3": "baz"})
}
Output:
target1:
echo from foo1
target2:
echo from bar2
target3:
echo from baz