dongpaipu8394 2013-04-22 07:19
浏览 55
已采纳

如何在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}}
  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件