用于源和目标打印的Golang模板

时间:2018-11-24 10:05:02

标签: templates go

我想生成带有循环的go模板,如下所示:

target1:
   echo from target2 
target2:
  echo from target2 
targetN:
  echo from targetN

这只是在之后创建目标和行 它会打印出从哪个目标调用。

我尝试了下面的部分工作方法,任何想法我在这里想念的是什么?或者如何简化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\n", buf.String())
}

1 个答案:

答案 0 :(得分:0)

这是您需要的吗?

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"})
}

输出:

target1:
    echo from target1
target2:
    echo from target2
target3:
    echo from target3

参考:https://golang.org/pkg/text/template/

更新

如果您要将管道用作地图,并希望使用相应键的值中的值,则:

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"})
}

输出:

target1:
    echo from foo1
target2:
    echo from bar2
target3:
    echo from baz