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

Nicolas Marshall picture Nicolas Marshall · Jul 3, 2014 · Viewed 32.7k times · Source

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

Answer

nvcnvn picture nvcnvn · Jul 3, 2014

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)