使用 go 模板创建 yaml 列表

use*_*080 5 go go-templates

我正在寻找以下格式的 yaml 文件。使用Go模板

  Custom_listeners:
    Config1 : config_value
    Config2 : config_value    

    copy_files:
      - source_path: /path/to/file.txt
        destination_path: /tmp/file.txt
Run Code Online (Sandbox Code Playgroud)

我正在使用以下模板代码来获取值

Template : 
custom_listeners:  {{ range $cl := $.Vars.CustomListeners }}
    {{ range $k,$v := $cl.Values }}{{ $k }}: "{{ $v }}"
    {{ end }}{{ end }}

Run Code Online (Sandbox Code Playgroud)
Custom listener map : 

type CustomListener map[string]interface{}
Run Code Online (Sandbox Code Playgroud)

我可以对上面的模板进行哪些更改来创建以下格式的 yaml。-在 source_path 上:

 Custom_listeners: 
   copy_files:
     - source_path1: /path/to/file.txt
       destination_path: /tmp/file.txt

     - source_path2: /path/to/file.txt
       destination_path: /tmp/file.txt
Run Code Online (Sandbox Code Playgroud)

Sou*_*ode 0

这是你想要的吗?

tmpStr := `Custom_listeners:
    {{ range $Custom_listener:=$.Custom_listeners }}{{ range $k,$v:=$Custom_listener }}{{ $k }}: {{ $v }}
    {{ end }}{{ end }}
copy_files:
  - source_path: {{ $.source_path }}
  destination_path: {{ $.destination_path }}
`
    data := map[string]any{
        "Custom_listeners": []map[string]string{
            {"Config1": "config_value"},
            {"Config2": "config_value"},
        },
        "source_path":      "/path/to/file.txt",
        "destination_path": "/tmp/file.txt",
    }

    tmp := template.New("yaml template")
    tmp, _ = tmp.Parse(tmpStr)
    tmp.Execute(os.Stdout, data)
Run Code Online (Sandbox Code Playgroud)

但为什么不使用像...“gopkg.in/yaml.v2”这样的 yaml 包?