1 回答

TA贡献1829条经验 获得超6个赞
带结构
你所拥有的是一个 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上试试这个变体。
- 1 回答
- 0 关注
- 176 浏览
添加回答
举报