使用go模板创建yaml列表



我希望创建以下格式的yaml文件。使用Go模板

Custom_listeners:
Config1 : config_value
Config2 : config_value    
copy_files:
- source_path: /path/to/file.txt
destination_path: /tmp/file.txt

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

Template : 
custom_listeners:  {{ range $cl := $.Vars.CustomListeners }}
{{ range $k,$v := $cl.Values }}{{ $k }}: "{{ $v }}"
{{ end }}{{ end }}
Custom listener map : 
type CustomListener map[string]interface{}

我可以对上面的模板进行哪些更改来创建以下格式的yaml。源路径上有-

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

这是您想要的吗?

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)

但是为什么不像…那样使用yaml包呢"gopkg.in/yaml.v2"?

最新更新