【问题标题】:Creating yaml list using the go template使用 go 模板创建 yaml 列表
【发布时间】:2023-02-07 13:00:27
【问题描述】:

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

  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。在 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

【问题讨论】:

标签: go go-templates


【解决方案1】:

这是你想要的吗?

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)

但为什么不使用“gopkg.in/yaml.v2”包呢?

【讨论】:

    猜你喜欢
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 2021-06-30
    • 2013-12-03
    • 2020-07-23
    • 1970-01-01
    相关资源
    最近更新 更多