您所拥有的是一个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
.