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}}
One of the predefined global template functions is index
.
index
Returns the result of indexing its first argument by the following arguments. Thusindex x 1 2 3
is, in Go syntax,x[1][2][3]
. Each indexed item must be amap
,slice
, orarray
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With