You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang模板中如何结合range与index遍历含短横线变量的值

How to Combine 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

  1. index .Values.something "something-else": This part fetches the value of the something-else key inside .Values.something. The index function 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.
  2. .values.list: Once we have the something-else object from index, we can use regular dot notation to access its values.list field like normal.
  3. range: We wrap the entire nested path in parentheses to ensure Go evaluates the index expression 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:43:18