代码之家  ›  专栏  ›  技术社区  ›  codec

如何发送地图数组并使用gin模板对其进行迭代

  •  2
  • codec  · 技术社区  · 8 年前

    下面是一段工作代码。我正在使用gin模板引擎。

    c.HTML(200, "index", gin.H{
                "title":    "Welcome",
                "students": map[int]map[string]string{1: {"PID": "1", "Name": "myName"}},})
    

     <TABLE class= "myTable" >
            <tr class="headingTr">
                <td>Name</td>
            </tr>
            {{range $student := .students}}
            <td>{{$student.Name}}</td>                    
            {{end}}
     </TABLE>
    

    如你所见,我已经硬编码了 students 在标题(地图)上。我想从我构建的rest API中获取这些数据。rest API的响应是一个数组:

     [
      {
        "id": 1,
        "name": "Mary"
      },
      {
        "id": 2,
        "name": "John"
      }
    ]
    

    我可以将此JSON响应解组为 map[string]string 而不是 map[int]map[string]string 。如何在参数值中为学生传递此未映射的主体,然后在该数组上迭代索引模板?

    1 回复  |  直到 8 年前
        1
  •  1
  •   icza    8 年前

    您所拥有的是一个JSON数组,将其解组为一个Go切片。建议创建 Student

    在模板中 {{range}} 行动决定成败 . 对于当前元素,可以在 身体就像点一样简单 . .Name .

    工作代码(在 Go Playground ):

    func main() {
        t := template.Must(template.New("").Parse(templ))
        var students []Student
        if err := json.Unmarshal([]byte(jsondata), &students); err != nil {
            panic(err)
        }
        params := map[string]interface{}{"Students": students}
        if err := t.Execute(os.Stdout, params); err != nil {
            panic(nil)
        }
    }
    
    const jsondata = `[
      {
        "id": 1,
        "name": "Mary"
      },
      {
        "id": 2,
        "name": "John"
      }
    ]`
    
    const templ = `<TABLE class= "myTable" >
            <tr class="headingTr">
                <td>Name</td>
            </tr>
            {{range .Students}}
            <td>{{.Name}}</td>                    
            {{end}}
     </TABLE>`
    

    输出:

    <TABLE class= "myTable" >
            <tr class="headingTr">
                <td>Name</td>
            </tr>
    
            <td>Mary</td>                    
    
            <td>John</td>                    
    
     </TABLE>
    

    带着地图

    如果您不想创建和使用 大学生 struct,您仍然可以使用类型为 map[string]interface{} 它可以表示任何JSON对象,但要知道,在这种情况下,必须将学生的姓名称为 .name 因为它在JSON文本中就是这样出现的,所以是小写的 "name" 键将用于非编组Go映射:

    func main() {
        t := template.Must(template.New("").Parse(templ))
        var students []map[string]interface{}
        if err := json.Unmarshal([]byte(jsondata), &students); err != nil {
            panic(err)
        }
        params := map[string]interface{}{"Students": students}
        if err := t.Execute(os.Stdout, params); err != nil {
            panic(nil)
        }
    }
    
    const templ = `<TABLE class= "myTable" >
            <tr class="headingTr">
                <td>Name</td>
            </tr>
            {{range .Students}}
            <td>{{.name}}</td>                    
            {{end}}
     </TABLE>`
    

    输出是相同的。在 Go Playground .