duagfgfn1981 2018-11-24 10:05
浏览 46
已采纳

用于源和目标打印的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())
}
  • 写回答

1条回答 默认 最新

  • dth981485742 2018-11-24 12:19
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答