在 Golang 模板中包含破折号的变量中的值范围

Range through values within variable containing dashes in Golang templates

我想遍历在 Golang 模板中包含破折号的变量下指定的值:

data:
  init: |
{{- range .Values.something.something-else.values.list }}
{{ . | indent 4 }}{{ end }}

我看到要从名称中带有破折号的变量访问值,应该使用 index 函数。

我不明白如何结合这两个功能。

index 函数记录在 text/template: Functions section:

index
    Returns the result of indexing its first argument by the
    following arguments. Thus "index x 1 2 3" is, in Go syntax,
    x[1][2][3]. Each indexed item must be a map, slice, or array.

要使用 index:传递要索引的值,以及要索引的值,例如

index . "Values" "something" "something-else" "values" "list"

结合{{range}}行动:

Items:
{{range index . "Values" "something" "something-else" "values" "list"}}
    {{.}},
{{end}}

查看简化的工作示例:

func main() {
    t := template.Must(template.New("").Parse(src))
    m := map[string]interface{}{
        "something": map[string]interface{}{
            "something-else": map[string]interface{}{
                "list": []string{"one", "two", "three"},
            },
        },
    }
    if err := t.Execute(os.Stdout, m); err != nil {
        panic(err)
    }
}

const src = `data:
{{- range index . "something" "something-else" "list" }} {{.}},{{ end }}`

输出(在 Go Playground 上尝试):

data: one, two, three,