Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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}}
like image 343
Nicolas Marshall Avatar asked Jul 03 '14 14:07

Nicolas Marshall


2 Answers

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)

like image 187
nvcnvn Avatar answered Oct 14 '22 22:10

nvcnvn


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

like image 2
Jonathan Bérubé Avatar answered Oct 15 '22 00:10

Jonathan Bérubé