我想显示一个表,每行都包含我的结构数据。
这是我的结构:
type My_Struct struct {
FIRST_FIELD string
SECOND_FIELD string
THIED_FIELD string
}
这是我的 html 代码:
<table id="t01">
<tr>
<th>FIRST FIELD</th>
<th>SECOND FIELD</th>
<th>THIRD FIELD</th>
</tr>
<tr>
<td>FIRST_OBJ_HERE_SHOULD_BE_THE_FIRST_FIELD</td>
<td>FIRST_OBJ_HERE_SHOULD_BE_THE_SECOND_FIELD</td>
<td>FIRST_OBJ_HERE_SHOULD_BE_THE_THIRD_FIELD</td>
</tr>
<tr>
<td>SECOND_OBJ_HERE_SHOULD_BE_THE_FIRST_FIELD</td>
<td>SECOND_OBJ_HERE_SHOULD_BE_THE_SECOND_FIELD</td>
<td>SECOND_OBJ_HERE_SHOULD_BE_THE_THIRD_FIELD</td>
</tr>
</table>
如您所见,我想将带有我的结构的切片(每个包含 3 个文件)传递给此 html 代码,并且我希望整个切片都将设置在此表中 - 每行包含一个结构数据。
我怎样才能做到这一点?
看起来你想要Go Template包。
下面是一个如何使用它的示例:定义一个处理程序,该处理程序将具有一些已定义字段的结构实例传递给使用 Go 模板的视图:
type MyStruct struct {
SomeField string
}
func MyStructHandler(w http.ResponseWriter, r *http.Request) {
ms := MyStruct{
SomeField: "Hello Friends",
}
t := template.Must(template.ParseFiles("./showmystruct.html"))
t.Execute(w, ms)
}
在您的视图 (showmystruct.html) 中使用 Go Template 语法访问结构字段:
<!DOCTYPE html>
<title>Show My Struct</title>
<h1>{{ .SomeField }}</h1>
更新
如果您对传递列表并对其进行迭代特别感兴趣,那么{{ range }}
关键字很有用。此外,有一个非常常见的模式(至少在我的世界中),您可以将PageData{}
结构传递给视图。
这是一个扩展示例,添加了一个PageData
结构体列表和一个结构体(因此我们可以在模板中访问其字段):
type MyStruct struct {
SomeField string
}
type PageData struct {
Title string
Data []MyStruct
}
func MyStructHandler(w http.ResponseWriter, r *http.Request) {
data := PageData{
Title: "My Super Awesome Page of Structs",
Data: []MyStruct{
MyStruct{
SomeField: "Hello Friends",
},
MyStruct{
SomeField: "Goodbye Friends",
},
}
t := template.Must(template.ParseFiles("./showmystruct.html"))
t.Execute(w, data)
}
和修改后的模板(showmystruct.html):
<!DOCTYPE html>
<title>{{ .Title }}</title>
<ul>
{{ range .Data }}
<li>{{ .SomeField }}</li>
{{ end }}
</ul>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句