How to range over slice of structs instead of struct of slices

依然范特西╮ 提交于 2019-12-03 17:33:25

问题


Having played around with Go HTML templates a bit, all the examples I found for looping over objects in templates were passing structs of slices to the template, somewhat like in this example :

type UserList struct {
    Id   []int
    Name []string
}

var templates = template.Must(template.ParseFiles("main.html"))

func rootHandler(w http.ResponseWriter, r *http.Request) {
    users := UserList{
        Id:   []int{0, 1, 2, 3, 4, 5, 6, 7},
        Name: []string{"user0", "user1", "user2", "user3", "user4"},
    }
    templates.ExecuteTemplate(w, "main", &users)
}

with the "main" template being :

{{define "main"}}
    {{range .Name}}
        {{.}}
    {{end}}
{{end}}

This works, but i don't understand how I'm supposed to display each ID just next to its corresponding Name if i'm ranging on the .Name property only. I would find it more logical to treat each user as an object to group its properties when displaying.

Thus my question:

What if I wanted to pass a slice of structs to the template? What would be the syntax to make this work? I haven't found or understood how to in the official html/template doc. I imagined something looking remotely like this:

type User struct {
    Id   int
    Name string
}
type UserList []User
var myuserlist UserList = ...

and a template looking somewhat like this: (syntax here is deliberately wrong, it's just to get understood)

{{define "main"}}
    {{for each User from myuserlist as myuser}}
        {{myuser.Id}}
        {{myuser.Name}}
    {{end}}
{{end}}

回答1:


Use:

{{range .}}
    {{.Id}}
    {{.Name}}
{{end}}

for the template.
Here is a example: http://play.golang.org/p/A4BPJOcfpB
You need to read more about the "dot" in the package overview to see how to properly use this. http://golang.org/pkg/text/template/#pkg-overview (checkout the Pipelines part)




回答2:


I don't have the rep to comment, but to answer @ROMANIA_engineer, the source cited by elithrar has been retired, for anyone still looking for this reference :

This book has been removed as it will shortly be published by APress. Please see Network Programming with Go: Essential Skills for Using and Securing Networks



来源:https://stackoverflow.com/questions/24556001/how-to-range-over-slice-of-structs-instead-of-struct-of-slices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!