Explain Index Function Like I'm 5

Can someone please explain the index function and give me some examples. Looks like a powerful GO function, but Hugo docs didn’t explain it in great details.

For example, these 2 lines below in partials/head.html:

{{ $author := index $.Site.Data.authors .Params.authorkey }}
{{ $dispname := ( index $author "en-US" ).display_name }}


authorkey: rickcogley
author: Rick Cogley
date: 2015-08-12T16:20:15+09:00


  display_name: Rick Cogley

Source: https://github.com/RickCogley/eSolia.pro/blob/master/layouts/partials/head.html

It’s not documented (although I think it should be) because it’s a function built-in to Go, not one we added with Hugo. From the godocs:

	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.

In Go templates, you can’t access array, slice, or map elements directly like you would in Go, as in $.Site.Data.authors[.Params.authorkey]. That syntax isn’t supported. You have to use a function that handles the lookup for you…that’s the job of the index function. It looks up the index(es) or key(s) of the data structure you pass it.

Hopefully, that’s “juice box and Jello pudding”-simple enough. :smiley_cat:

1 Like