如何将多个对象传递给 Go html 模板

Pri*_*nka 3 go go-html-template

这是我的对象数组,

type PeopleCount []struct{
   Name  string
   Count int
}

type Consultation []struct{
   Name          string
   Opd_count     int
   Opinion_count int
   Req_count     int
}
Run Code Online (Sandbox Code Playgroud)

我应该如何将两个对象传递给 html 模板并将它们排列在表格中?

Cer*_*món 5

定义一个包含人数统计和咨询字段的匿名结构,并将该结构传递给模板 Execute 方法:

var data = struct {
    PeopleCounts  []PeopleCount
    Consultations []Consultation
}{
    PeopleCounts:  p,
    Consultations: c,
}
err := t.Execute(w, &data)
if err != nil {
    // handle error
}
Run Code Online (Sandbox Code Playgroud)

在模板中使用这些字段:

{{range .PeopleCounts}}{{.Name}}
{{end}}
{{range .Consultations}}{{.Name}}
{{end}}
Run Code Online (Sandbox Code Playgroud)

游乐场示例

您可以为模板数据声明一个命名类型。匿名类型声明的优点是模板数据的知识本地化到调用模板的函数。

您还可以使用地图而不是类型:

err := t.Execute(w, map[string]interface{}{"PeopleCounts": p, "Consultations": c})
if err != nil {
    // handle error
}
Run Code Online (Sandbox Code Playgroud)

使用地图的缺点是模板中的拼写错误可能不会导致错误。例如,``{{range .PopleConts}}{{end}}` silent 什么都不做。

上面的代码假设 PeopleCount 和 Consultation 是结构类型而不是匿名结构类型的切片:

type PeopleCount struct {
  Name  string
  Count int
}

type Consultation struct {
  Name          string
  Opd_count     int
  Opinion_count int
  Req_count     int
}
Run Code Online (Sandbox Code Playgroud)

给元素一个命名类型通常比给切片一个命名类型更方便。