douyou7072 2016-05-07 13:23
浏览 63

Golang:在Go模板中按切片排序地图

I have a question about how to order a map by a slice in Go Templates and if it is possible.

Problem: I have a slice of ordered variable names that I want to display on a website, accompanying them I have a map of metadata of variable information that I would like to display together with the variable.

If I have the following struct that I pass in to the template:

type Data struct {
       Variables    []string
       Information  map[string]int
}

I would iterate over the slice and pass the variable name in to the map

{{ range $v := .Variables }} {{ index .Information $v }} {{ end }} // Doesn't work.

Here's a Go Playground with the example. https://play.golang.org/p/AL2csnXdoU

Question: How can I do this?

I am fairly new to Golang. Thankful for any input.

  • 写回答

1条回答 默认 最新

  • douyi3767 2016-05-07 13:47
    关注

    The following should work. To access .Information inside range, you should use $, which is basically d in your Playground example.

    {{ range .Variables }} {{ index $.Information . }} {{ end }}
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?