问题
I want to show a table that each row contains my struct data.
Here is my struct:
type My_Struct struct {
FIRST_FIELD string
SECOND_FIELD string
THIED_FIELD string
}
Here is my html code:
<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>
As you see, I want to pass a slice with my struct (each one contains 3 files) to this html code, and I want the the whole slice will be set in this table - each row contains one struct data.
How can I achieve this?
回答1:
It seems like you want the Go Template package.
Here's an example of how you may use it: Define a handler that passes an instance of a struct with some defined field(s) to a view that uses Go Templates:
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)
}
Access the struct fields using the Go Template syntax in your view (showmystruct.html):
<!DOCTYPE html>
<title>Show My Struct</title>
<h1>{{ .SomeField }}</h1>
Update
If you are interested particularly in passing a list, and iterating over that, then the {{ range }}
keyword is useful. Also, there's a pretty common pattern (at least in my world) where you pass a PageData{}
struct to the view.
Here's an expanded example, adding a list of structs, and a PageData
struct (so we can access its fields in the template):
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)
}
And the modified template (showmystruct.html):
<!DOCTYPE html>
<title>{{ .Title }}</title>
<ul>
{{ range .Data }}
<li>{{ .SomeField }}</li>
{{ end }}
</ul>
来源:https://stackoverflow.com/questions/56305805/how-to-show-a-table-from-a-slice-with-my-struct