gogo-templatesconsul-template

How to get key from map


I'm working on go template. Having some map in . I know how to get the value, as long as I know the key.

"Map value: {{ printf "%s" .key1 }}"

How to get key name from inside the template? I would expect maybe something like

"Map key: {{ printf "%s" (keys .)[0] }}"

Solution

  • As @Adrian commented:

    {{ range $key, $val := . }}
    key: {{ $key }}; value: {{ $val }}
    {{ end }}
    

    But it was hard to figure it out just from range documentation