2

Following is the snippet of a working code. I am using gin templating engine.

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

And in index template I have:

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

As you can see I have hard-coded the value of students on the headers (the map). I want to have this data from a rest API that I have built. the response of my rest API is an array:

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

I can unmarshal this JSON response into map[string]string instead of map[int]map[string]string. How can pass this unmarhsaled body in parameter value for students and then iterate over this array the index template?

4

1 回答 1

1

带结构

你所拥有的是一个 JSON 数组,将它解组为一个 Go 切片。建议创建一个Student结构来为您的学生建模,以获得干净且有意识的 Go 代码。

并且在模板中,{{range}}动作将点.设置为当前元素,您可以在{{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>

带地图

如果您不想创建和使用Student结构,您仍然可以使用类型为的简单映射来完成,该映射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上试试这个变体。

于 2016-08-23T08:50:35.433 回答