【问题标题】:How to pass multiple objects to Go html template如何将多个对象传递给 Go html 模板
【发布时间】:2015-09-12 06:53:03
【问题描述】:

这是我的对象数组,

type PeopleCount []struct{
   Name  string
   Count int
}

type Consultation []struct{
   Name          string
   Opd_count     int
   Opinion_count int
   Req_count     int
}

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

【问题讨论】:

    标签: go go-html-template


    【解决方案1】:

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

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

    在模板中使用这些字段:

    {{range .PeopleCounts}}{{.Name}}
    {{end}}
    {{range .Consultations}}{{.Name}}
    {{end}}
    

    Playground example

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

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

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

    使用地图的缺点是模板中的拼写错误可能不会导致错误。例如,`{{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
    }
    

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

    【讨论】:

      【解决方案2】:

      如果您愿意,可以定义一个未导出的结构,其中包含人数统计和咨询字段,并将该结构传递给模板 Execute 方法:

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

      这种方法与@Bravada 的回答大体相似。显式还是匿名使用视图模型类型只是个人喜好问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-15
        • 2017-06-17
        • 2017-08-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-29
        • 2012-10-09
        相关资源
        最近更新 更多