【发布时间】:2019-11-17 07:05:14
【问题描述】:
我想在 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
...
我不明白如何连接一张表中的所有单元格
索引.html: https://drive.google.com/file/d/1HzEL0i3VhiafPzlV8iC0kU8WaSQwoYZY/view?usp=sharing
【问题讨论】:
-
您应该首先将数据聚合到一个切片中,然后,在模板中,您可以使用
range操作循环该切片并呈现各个行。目前,您在单独的index.html文件中单独渲染每一行,这是错误的。此外,您应该在问题中包含模板代码,而不是在 SO 之外链接到它。