以下是工作代码的片段。我正在使用 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>
如您所见,我在标题( map )上硬编码了 students
的值。我想从我构建的 rest API 中获取这些数据。我的其余 API 的响应是一个数组:
[
{
"id": 1,
"name": "Mary"
},
{
"id": 2,
"name": "John"
}
]
我可以将此 JSON 响应解码为 map[string]string
而不是 map[int]map[string]string
。如何将这个未编码的主体传递给学生的参数值,然后遍历索引模板的这个数组?
最佳答案
有一个结构
您拥有的是一个 JSON 数组,将其解码为 Go slice 。建议创建一个 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>
有 map
如果您不想创建和使用 Student
结构,您仍然可以使用类型为 map[string]interface{}
的简单映射来实现它可以表示任何 JSON 对象,但要知道,在这种情况下,您必须将学生的姓名称为 .name
,因为它在 JSON 文本中是这样显示的,所以 "name 是小写的"
key 将在未编码的 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 上试试这个变体.
关于json - 如何发送一组 map 并使用 gin-templating 对其进行迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39096335/