Iterating through map in template

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

Iterating through map in template

问题

我正在尝试显示一个健身课程列表(瑜伽、普拉提等)。对于每种课程类型,都有几个具体的课程,所以我想将所有瑜伽课程分组,所有普拉提课程分组,以此类推。

我编写了以下函数来对切片进行分组并生成一个映射:

func groupClasses(classes []entities.Class) map[string][]entities.Class {
    classMap := make(map[string][]entities.Class)
    for _, class := range classes {
        classMap[class.ClassType.Name] = append(classMap[class.ClassType.Name], class)
    }
    return classMap
}

问题是如何遍历这个映射。根据http://golang.org/pkg/text/template/的说明,你需要以.Key的格式访问它,但我不知道这些键(除非我还将键的切片传递到模板中)。我该如何在视图中解包这个映射。

目前我只有这样的代码:

{{ . }}

它显示的结果类似于:

map[Pilates:[{102 PILATES ~/mobifit/video/ocen.mpg 169 40 2014-05-03 23:12:12 +0000 UTC 2014-05-03 23:12:12 +0000 UTC 1899-12-30 00:00:00 +0000 UTC {PILATES Pilates 1 2014-01-22 21:46:16 +0000 UTC} {1 leebrooks0@gmail.com password SUPERADMIN Lee Brooks {Male true} {1990-07-11 00:00:00 +0000 UTC true} {1.85 true} {88 true} 2014-01-22 21:46:16 +0000 UTC {0001-01-01 00:00:00 +0000 UTC false} {0001-01-01 00:00:00 +0000 UTC false} {0001-01-01 00:00:00 +0000 UTC false}} [{1 Mat 2014-01-22 21:46:16 +0000 UTC}]} {70 PILATES ~/mobifit/video/ocen.mpg 119 66 2014-03-31 15:12:12 +0000 UTC 2014-03-31 15:12:12 +0000 UTC 1899-12-30 00:00:00 +0000 UTC
英文:

I am trying to display a list gym classes (Yoga, Pilates etc). For each class type there are several classes, so I want to group all the Yoga classes, and all the Pilates classes and so on.

I made this function to take a slice and make a map of it

func groupClasses(classes []entities.Class) map[string][]entities.Class {
	classMap := make(map[string][]entities.Class)
	for _, class := range classes {
		classMap[class.ClassType.Name] = append(classMap[class.ClassType.Name], class)
	}
	return classMap
}

The problem is now how can I iterate through it, according to http://golang.org/pkg/text/template/, you need to access it in .Key format, I don't know the keys (unless I also passed a slice of keys into the template). How do I unpack this map in my view.

All I have currently is

{{ . }} 

which displays something like:

map[Pilates:[{102 PILATES ~/mobifit/video/ocen.mpg 169 40 2014-05-03 23:12:12 +0000 UTC 2014-05-03 23:12:12 +0000 UTC 1899-12-30 00:00:00 +0000 UTC {PILATES Pilates 1 2014-01-22 21:46:16 +0000 UTC} {1 leebrooks0@gmail.com password SUPERADMIN Lee Brooks {Male true} {1990-07-11 00:00:00 +0000 UTC true} {1.85 true} {88 true} 2014-01-22 21:46:16 +0000 UTC {0001-01-01 00:00:00 +0000 UTC false} {0001-01-01 00:00:00 +0000 UTC false} {0001-01-01 00:00:00 +0000 UTC false}} [{1 Mat 2014-01-22 21:46:16 +0000 UTC}]} {70 PILATES ~/mobifit/video/ocen.mpg 119 66 2014-03-31 15:12:12 +0000 UTC 2014-03-31 15:12:12 +0000 UTC 1899-12-30 00:00:00 +0000 UTC 

答案1

得分: 226

请查看Go模板文档中的变量部分。range语句可以声明两个变量,用逗号分隔。以下代码应该可以工作:

{{ range $key, $value := . }}
   <li><strong>{{ $key }}</strong>: {{ $value }}</li>
{{ end }}
英文:

Check the Variables section in the Go template docs. A range may declare two variables, separated by a comma. The following should work:

{{ range $key, $value := . }}
   <li><strong>{{ $key }}</strong>: {{ $value }}</li>
{{ end }}

答案2

得分: 52

如Herman所指出的,你可以从每次迭代中获取索引和元素。

{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}

工作示例:

package main

import (
    "html/template"
    "os"
)

type EntetiesClass struct {
    Name  string
    Value int32
}

// 在模板中,我们使用rangeStruct将我们的结构值转换为可以迭代的切片
var htmlTemplate = `{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}`

func main() {
    data := map[string][]EntetiesClass{
        "Yoga":    {{ "Yoga", 15 }, { "Yoga", 51 }},
        "Pilates": {{ "Pilates", 3 }, { "Pilates", 6 }, { "Pilates", 9 }},
    }

    t := template.New("t")
    t, err := t.Parse(htmlTemplate)
    if err != nil {
        panic(err)
    }

    err = t.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }
}

输出:

Pilates
3
6
9

Yoga
15
51

Playground: http://play.golang.org/p/4ISxcFKG7v

英文:

As Herman pointed out, you can get the index and element from each iteration.

{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}

Working example:

package main

import (
    "html/template"
    "os"
)

type EntetiesClass struct {
	Name string
	Value int32
}

// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}`

func main() {
    data := map[string][]EntetiesClass{
        "Yoga": {{"Yoga", 15}, {"Yoga", 51}},
        "Pilates": {{"Pilates", 3}, {"Pilates", 6}, {"Pilates", 9}},
    }

    t := template.New("t")
    t, err := t.Parse(htmlTemplate)
    if err != nil {
        panic(err)
    }

    err = t.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }

}

Output:

Pilates
3
6
9

Yoga
15
51

Playground: http://play.golang.org/p/4ISxcFKG7v

huangapple
  • 本文由 发表于 2014年1月23日 16:01:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/21302520.html
匿名

发表评论

匿名网友

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

确定