简体   繁体   English

如何在结构片的范围内而不是在切片的结构上范围

[英]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 : 在玩过Go HTML模板后,我发现所有用于遍历模板中对象的示例都是将切片的结构传递给模板,有点像此示例中所示:

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. 这有效,但是如果我仅使用.Name属性,则我不明白如何在每个ID旁边显示每个ID。 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. 我尚未在官方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}}

Use: 使用:

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

for the template. 为模板。
Here is a example: http://play.golang.org/p/A4BPJOcfpB 这是一个示例: 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) http://golang.org/pkg/text/template/#pkg-overview (检出“管道”部分)

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 : 我没有发表评论的代表,但是想要回复@ ROMANIA_engineer,elithrar引用的源已被淘汰,对于仍在寻找此参考文献的任何人:

This book has been removed as it will shortly be published by APress. 这本书已被删除,因为APress不久将出版。 Please see Network Programming with Go: Essential Skills for Using and Securing Networks 请参阅Go语言网络编程:使用和保护网络的基本技能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM