Iterating through map in template

前端 未结 2 1199
名媛妹妹
名媛妹妹 2020-12-23 14:04

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 cl

相关标签:
2条回答
  • 2020-12-23 14:55

    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

    0 讨论(0)
  • 2020-12-23 14:59

    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 }}
    
    0 讨论(0)
提交回复
热议问题