如何使用html / template中的范围内的索引来遍历并行数组? [英] how to use index inside range in html/template to iterate through parallel arrays?
问题描述
我正在执行一个具有2个并行数组(相同大小)的模板,我想从两个数组中并行列出项目,如何在范围内使用索引?
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}}
推荐答案
其中一个预定义的全局模板函数是 index
。
$ b
One of the predefined global template functions is index
.
index
返回$ b的第一个参数的索引结果$ b以下参数。因此,在Go语法中,index x 1 2 3
是
x [1] [2] [3]
。每个索引项必须是map
,切片
或数组
。
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.
所以你需要回到原来的点,因为我们有以下几点:$ b
$ b
So you need to get back to the original dot, for that we have the following
<当执行开始时,$
被设置为传递给Execute的数据参数,也就是点的起始值。
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}}
个人而言,我会创建一个名为 zip
的模板函数,它接受多个切片并返回每对值的一部分。它会在你的模板中看起来更干净,并可能在某处被重用。
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.
这篇关于如何使用html / template中的范围内的索引来遍历并行数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!