How to index a slice element?
Asked Answered
C

2

59

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.

Chaiken answered 3/10, 2012 at 3:24 Comment(0)
C
96

Use the index command like so:

{{index .Keys 3}}
Cornew answered 3/10, 2012 at 3:31 Comment(3)
@DeanSinaean: From the Overview of the html/template documentation: "For information about how to program the templates themselves, see the documentation for text/template."Simar
@Cornew do you know how to avoid getting index out of range problem ?Micropyle
@Micropyle 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.Cornew
D
35

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.
Debroahdebs answered 3/10, 2012 at 3:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.