我想在go package" temlate"中在html中制作表
我的代码:
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)
}
我得到了这个:
Devices
Type Name Param Time Value
devicetype iddevice devicename oidname value
Devices
Type Name Param Time Value
devicetype iddevice devicename oidname value
...
但是我想要这样的东西
Devices
Type Name Param Time Value
devicetype iddevice devicename oidname value
devicetype iddevice devicename oidname value
...
i不透露如何连接一个表中的所有单元
index.html:https://drive.google.com/file/d/1hzel0i3vhiafpzlv8ic0ku8wasqwoyzy/view?usp = sharing
,因为您在for loop
中执行模板。您也可以通过一个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)
}
您还必须通过数据迭代并动态生成行。
<!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>