Golang模板中如何结合range与index遍历含短横线变量的值
index and range for Keys with Hyphens in Go Templates Got it, let's break this down for you. The core issue here is that Go template identifiers can't include hyphens, so you can't directly access .Values.something.something-else like you would with regular snake_case or camelCase keys. That's where the index function comes in—and combining it with range is straightforward once you know the pattern.
Let's Start with the Fix
First, here's the corrected version of your template code that uses index to access the hyphenated key, then pairs it with range:
data: init: | {{- range (index .Values.something "something-else").values.list }} {{ . | indent 4 }} {{ end }}
Breaking It Down
index .Values.something "something-else": This part fetches the value of thesomething-elsekey inside.Values.something. Theindexfunction takes a map/struct and a key (as a string) to retrieve the nested value—perfect for keys with hyphens that can't be accessed via direct dot notation..values.list: Once we have thesomething-elseobject fromindex, we can use regular dot notation to access itsvalues.listfield like normal.range: We wrap the entire nested path in parentheses to ensure Go evaluates theindexexpression first, then iterates over the resulting list.
A More Readable Alternative (Using with)
If you're working with multiple fields under something-else, using with to bind the result of index to a local context can make your template cleaner:
data: init: | {{- with index .Values.something "something-else" }} {{- range .values.list }} {{ . | indent 8 }} {{- end }} {{- end }}
The with block sets the current context (.) to the something-else value, so inside the block, you can use .values.list directly without repeating the index call. This is especially useful if you need to access other fields from something-else later in the template.
Why Your Original Code Failed
Your original line {{- range .Values.something.something-else.values.list }} throws an error because Go templates treat something-else as an invalid identifier (hyphens aren't allowed in identifiers). The index function bypasses this by letting you reference the key as a string literal instead.
内容的提问来源于stack exchange,提问作者supercalifragilistichespirali

