如何在html/template中使用索引来遍历并行数组?

huangapple go评论92阅读模式
英文:

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

问题

我正在执行一个模板,其中包含两个并行数组(大小相同),我想要并行地列出两个数组中的项目,如何在range内部使用索引?

显然,下面的代码是不起作用的:

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

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}}

答案1

得分: 19

其中一个预定义的全局模板函数index

> index 返回其第一个参数通过后续参数索引的结果。因此,在Go语法中,index x 1 2 3等同于x[1][2][3]。每个索引项必须是mapslicearray

所以你走在正确的轨道上。唯一的问题是你没有考虑到dotrange块内被重新赋值的事实。

所以你需要回到原始的dot,为此我们有以下内容:

> 当执行开始时,$被设置为传递给Execute的数据参数,也就是dot的初始值。

所以(假设你的模板中没有其他操作),你应该可以这样做:

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

个人而言,我会创建一个名为zip的模板函数,它接受多个切片并返回每对值的切片。在你的模板中,它看起来更清晰,而且可能会在其他地方重复使用。

英文:

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.

huangapple
  • 本文由 发表于 2013年4月22日 15:19:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/16141467.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定