Reputation: 59
I want to make the table in HTML in go package "temlate" and i want to add rows in loop, but i didn't find how doing this
my code:
package main
import (
"net/http"
"html/template"
)
type Devicevalue_view struct {
Devicetype string
Iddevice string
Devicename string
Oidname string
Value string
}
func page_1(w http.ResponseWriter, r *http.Request){
for i:=1; i<10; i++{
data := Devicevalue_view{
Devicetype: "devicetype",
Iddevice: "iddevice",
Devicename: "devicename",
Oidname: "oidname",
Value: "value",
}
tmpl, _ := template.ParseFiles("./index.html")
tmpl.Execute(w, data)
}
}
func main() {
http.HandleFunc("/table", page_1)
http.ListenAndServe(":3000", nil)
}
i'm getting this :
Devices
Type Name Param Time Value
devicetype iddevice devicename oidname value
Devices
Type Name Param Time Value
devicetype iddevice devicename oidname value
...
but i want somthing like this
Devices
Type Name Param Time Value
devicetype iddevice devicename oidname value
devicetype iddevice devicename oidname value
...
I don't undestand how connect all cells in one table
index.html: https://drive.google.com/file/d/1HzEL0i3VhiafPzlV8iC0kU8WaSQwoYZY/view?usp=sharing
Upvotes: 0
Views: 6829
Reputation: 3657
Because you are executing template inside for loop
. Also you can pass a single struct
. To pass array you have to pass it as a member of the struct.
package main
import (
"html/template"
"net/http"
)
type Data struct {
Items []Devicevalue_view
}
type Devicevalue_view struct {
Devicetype string
Iddevice string
Devicename string
Oidname string
Value string
}
func page_1(w http.ResponseWriter, r *http.Request) {
data := Data{}
for i := 1; i < 10; i++ {
view := Devicevalue_view{
Devicetype: "devicetype",
Iddevice: "iddevice",
Devicename: "devicename",
Oidname: "oidname",
Value: "value",
}
data.Items = append(data.Items, view)
}
tmpl, _ := template.ParseFiles("./index.html")
tmpl.Execute(w, data)
}
func main() {
http.HandleFunc("/table", page_1)
http.ListenAndServe(":3000", nil)
}
Also you have to iterate through data and generate row dynamically.
<!DOCTYPE html>
<html lang="en">
<body>
<table>
<tr>
<th>Type</th>
<th>Name</th>
<th>Param</th>
<th>Time</th>
<th>Value</th>
</tr>
{{ range .Items}}
<tr>
<td>{{ .Devicetype }}</td>
<td>{{ .Iddevice }}</td>
<td>{{ .Devicename }}</td>
<td>{{ .Oidname }}</td>
<td>{{ .Value }}</td>
</tr>
{{ end}}
</table>
</body>
</html>
Upvotes: 9