Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use index inside range in html/template to iterate through parallel arrays?

Tags:

go

I'm executing a template with 2 parallel arrays (same size) and I want to list items from both arrays in parallel, how do I use index inside of range?

this obviously doesn't work:

{{range $i, $e := .First}}$e - {{index .Second $i}}{{end}}
like image 298
Gal Ben-Haim Avatar asked Apr 22 '13 07:04

Gal Ben-Haim


1 Answers

One of the predefined global template functions is index.

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.

So you are on the right track. The only issue is that you are not accounting for the fact the dot has been reassigned within the range block.

So you need to get back to the original dot, for that we have the following

When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.

So (assuming there is nothing else going on in your template) you should be able to do:

{{range $i, $e := .First}}$e - {{index $.Second $i}}{{end}}

Personally though, I would create a template function called zip that accepts multiple slices and returns a slice of each pair of values. It would look cleaner in your template and probably get reused somewhere.

like image 103
Chris Farmiloe Avatar answered Sep 27 '22 22:09

Chris Farmiloe