如何使用我的结构显示切片中的表格

我想显示一个表,其中每一行都包含我的结构数据。


这是我的结构:


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 代码,并且我希望整个切片将设置在此表中 - 每行包含一个结构数据。


我怎样才能做到这一点?


梦里花落0921
浏览 65回答 1
1回答

jeck猫

看起来你想要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>
打开App,查看更多内容
随时随地看视频慕课网APP