2014-01-23 1 views
55

목록 체육관 수업 (요가, 필라테스 등)을 표시하려고합니다. 각 클래스 유형에는 여러 클래스가 있으므로 모든 요가 클래스와 모든 필라테스 클래스 등을 그룹화하려고합니다.템플릿을 통한지도 반복

내가 http://golang.org/pkg/text/template/에 따라, 당신은 .Key 형식으로 접근 할 필요가, 조각을 내가 그것을 통해 반복 할 수있는 방법 문제는 지금

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 
} 

그것의지도를 만들기 위해이 기능을 만든

, I 키를 모르는 경우 (템플릿에 키 조각을 전달하지 않은 경우). 내지도에서이지도의 압축을 풀려면 어떻게해야합니까?

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 [email protected] 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 

답변

100

가 이동 템플릿 문서에 Variables section을 확인합니다

내가 가진 모든 현재 같은 것을 표시

{{ . }} 

입니다. 범위는 두 변수를 쉼표로 구분하여 선언 할 수 있습니다. 다음은 작동해야합니다 :

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

Herman이 지적했듯이 Herman은 지적한대로 각 반복에서 색인과 요소를 얻을 수 있습니다.

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

근무 예 :

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

} 

출력 :

Pilates 
3 
6 
9 

Yoga 
15 
51 

놀이터 : http://play.golang.org/p/4ISxcFKG7v

+0

이 코드 예제 – Lee

+1

@lee에 오신 것을 환영합니다 주셔서 너무 감사합니다! :) 허먼이 이미 당신에게 정답을 주었다고 할지라도 그것을 사용한다고 생각했습니다. – ANisus