How to range over slice of structs instead of struct of slices
Asked Answered
T

2

15

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}}
Tzong answered 3/7, 2014 at 14:9 Comment(4)
Read this: jan.newmarch.name/go/template/chapter-template.html - specifically, assign one to a variable that you can call from within the range loop.Scoutmaster
That seems to be quite complete on the subject, i'll be sure to read all of it very soon. Thanks.Tzong
Indeed, it even had the answer to problems i guessed i would run into later. Thanks for this great link.Tzong
@Scoutmaster , can you add a valid URL?Cephalochordate
C
45

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)

Collaboration answered 3/7, 2014 at 14:27 Comment(0)
E
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

Elative answered 22/7, 2017 at 20:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.