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

超能力主义螺旋体:

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

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

我已经看到index应该使用name 函数中带有破折号的变量访问值

我不明白如何将两个功能结合在一起。

icza:

index功能记录在text/template:功能部分

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,

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章