Golang模板中无法遍历用户列表怎么办

Golang模板中无法遍历用户列表怎么办 main.go 代码:

type User struct {
name string
age  int8
}
...
...
tmpl := template.Must(template.ParseFiles("todo.html"))
user1 := User{name: "one", age: 16}
user2 := User{name: "two", age: 17}
user3 := User{name: "three", age: 16}
users := []User{user1, user2, user3}
tmpl.Execute(w, users)
...
...

我的 HTML 模板:

{{range .}}
{{.name}}
{{end}}

问题出在哪里? 为了调试,当我在 HTML 页面中只打印 {{.}} 时,它显示如下内容:

{one 16}
{two 17}
{three 16}

为什么我无法访问任何属性?


更多关于Golang模板中无法遍历用户列表怎么办的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

找到了错误,我本应输入 Name 而不是 name。这不是我代码中的错误,而是 Go 语言一个非常奇怪的行为(即每个字段都必须以大写字母开头)。

我应该花更多时间阅读关于“Effective Go”的文档。

更多关于Golang模板中无法遍历用户列表怎么办的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


问题在于Go模板中访问结构体字段时需要使用导出字段(首字母大写)。在Go语言中,只有导出的字段才能在模板中被访问。

修改你的结构体定义,将字段首字母大写:

type User struct {
    Name string // 首字母大写
    Age  int8   // 首字母大写
}

同时更新创建用户的代码:

user1 := User{Name: "one", Age: 16}
user2 := User{Name: "two", Age: 17}
user3 := User{Name: "three", Age: 16}
users := []User{user1, user2, user3}

HTML模板保持不变即可正常工作:

{{range .}}
{{.Name}}  <!-- 注意这里也要用大写 -->
{{end}}

或者如果你想在模板中同时显示年龄:

{{range .}}
用户:{{.Name}},年龄:{{.Age}}
{{end}}

如果因为某些原因不能修改结构体字段的导出性,可以使用模板函数来访问私有字段,但这不是推荐的做法:

func (u User) GetName() string {
    return u.name
}

func (u User) GetAge() int8 {
    return u.age
}

然后在模板中:

{{range .}}
{{.GetName}} - {{.GetAge}}
{{end}}
回到顶部