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

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源