57

I have a slice: Keys []* datastore.Key

How could I index one of them in the template file? I guessed {{.Keys[3] }}, but that doesn't work and I searched a lot but with no clue.

Any suggestions would be welcome, thanks.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
DeanSinaean
  • 2,297
  • 4
  • 16
  • 19

2 Answers2

94

Use the index command like so:

{{index .Keys 3}}
nemo
  • 55,207
  • 13
  • 135
  • 135
  • 1
    @DeanSinaean: From the Overview of the `html/template` documentation: "For information about how to program the templates themselves, see the documentation for text/template." – Jonathan Hall May 15 '18 at 15:55
  • @nemo do you know how to avoid getting index out of range problem ? – sh0umik Mar 28 '20 at 09:04
  • 1
    @sh0umik What kind of problem do you mean? You are getting index out of range errors when accessing elements that are not in said array. There is no special trick to avoid this, just don't do it. If you want a 'safe' indexing method, you can always write your own function to access data which will handle out of bounds errors on its own. – nemo Mar 30 '20 at 13:55
33

As stated in the html/template package, the majority of examples are actually located in the text/template pkg docs. See http://golang.org/pkg/text/template/

From the docs

index
    Returns the result of indexing its first argument by the
    following arguments. Thus "index x 1 2 3" is, in Go syntax,
    x[1][2][3]. Each indexed item must be a map, slice, or array.
dskinner
  • 10,527
  • 3
  • 34
  • 43