Search code examples
kubernetes-helmgo-templates

Helm template prefixes range index with an underscore


We can access the index by this way :

{{- range $i, $s := (some list) }}
{{$i}}
{{-end }}

output:
0
1
..etc

However when the list is a result of a string split, the index becomes prefixed with an underscore

{{- range $i, $s := (split "X" "aaXbbXcc") }}
{{$i}}
{{-end }}

output:
_0
_1
..etc

why?


Solution

  • The split function returns a dict, whose index members are prefixed with a _ character before. It is useful when you are planning to use dot notation for accessing members and not ideally suited for iteration with range.

    For accessing the result as a list of strings with their indices, use splitList. See documentation for more information

    {{- range $i, $s := (splitList "X" "aaXbbXcc") }}
    {{$i}}
    {{- end }}