如何在切片的结构范围内而不是切片的结构范围内 [英] How to range over slice of structs instead of struct of slices

查看:87
本文介绍了如何在切片的结构范围内而不是切片的结构范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Go HTML模板进行了一些尝试,发现所有用于遍历模板中对象的示例都是将切片的结构传递给模板,就像这个示例中一样:

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

主"模板为:

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

这有效,但是如果我仅在.Name属性范围内,我不明白应该如何在每个ID旁边显示每个ID.我会发现在显示时将每个用户视为一个对象来对其属性进行分组是更合乎逻辑的.

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.

我的问题是

如果我想将一片结构传递给模板怎么办?使该工作生效的语法是什么?我尚未在官方html/template文档中找到或了解如何进行操作. 我想像的东西看起来像这样:

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

推荐答案

使用:

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

作为模板.
这是一个示例: http://play.golang.org/p/A4BPJOcfpB
您需要在包装概述中阅读有关点"的更多信息,以了解如何正确使用它. http://golang.org/pkg/text/template/#pkg-overview(签出管道"部分)

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)

这篇关于如何在切片的结构范围内而不是切片的结构范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆