-2

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] }}"
BartBiczBoży
  • 2,512
  • 2
  • 24
  • 33
  • 5
    You can `range` over a map to get *all* the keys and values, is that what you're looking for? There's no meaningful way to get a slice of the keys you can access by numeric index because slices are ordered and maps are not. – Adrian Dec 21 '18 at 15:31
  • @Adrian yes, sounds like what I need. – BartBiczBoży Dec 21 '18 at 15:32
  • 1
    `range` is covered in the documentation under Actions: https://golang.org/pkg/text/template/#hdr-Actions – Adrian Dec 21 '18 at 15:36
  • @Adrian Thanks, I can see it and it works indeed. Just don't want to put an answer when it is you who actually gave it. – BartBiczBoży Dec 21 '18 at 15:39

2 Answers2

2

As @Adrian commented:

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

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

BartBiczBoży
  • 2,512
  • 2
  • 24
  • 33
0

Since the question is tagged with consul-template... the syntax for Consul/Vault templates is (given .Data is the map):

{{ index .Data "complex.key.name" }}

This is useful, when the the key name is complex (say contains dots) and {{ .Data.complex.key.name }} is interpreted as accessing nested fields.

WindyFields
  • 2,697
  • 1
  • 18
  • 21