How to index a slice element?

SliceGo Templates

Slice Problem Overview


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.

Slice Solutions


Solution 1 - Slice

Use the index command like so:

{{index .Keys 3}}

Solution 2 - Slice

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDeanSinaeanView Question on Stackoverflow
Solution 1 - SlicenemoView Answer on Stackoverflow
Solution 2 - SlicedskinnerView Answer on Stackoverflow