2013-04-22 07:19
浏览 48

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

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

图片转代码服务由CSDN问答提供 功能建议

我正在执行带有2个并行数组(相同大小)的模板,并且我希望在这两个数组中列出项目 并行,如何在范围内使用索引?


  {{range $ i,$  e:= .First}} $ e-{{index .Second $ i}} {{end}} 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • du4373 2013-04-22 08:13

    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.

    解决 无用
    打赏 举报

相关推荐 更多相似问题