go html 模板表

Сер*_*сов 0 html templates loops go

我想在 go 包“模板”中用 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)
}
Run Code Online (Sandbox Code Playgroud)

我得到这个:


Devices
Type    Name    Param   Time    Value
devicetype  iddevice    devicename  oidname value
Devices
Type    Name    Param   Time    Value
devicetype  iddevice    devicename  oidname value
...
Run Code Online (Sandbox Code Playgroud)

但我想要这样的东西

Devices
Type    Name    Param   Time    Value
devicetype  iddevice    devicename  oidname value
devicetype  iddevice    devicename  oidname value
...
Run Code Online (Sandbox Code Playgroud)

我不明白如何连接一张表中的所有单元格

index.html:https : //drive.google.com/file/d/1HzEL0i3VhiafPzlV8iC0kU8WaSQwoYZY/view? usp =sharing

Sha*_*uza 5

因为你在里面执行模板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)
}
Run Code Online (Sandbox Code Playgroud)

此外,您必须遍历数据并动态生成行。

<!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>
Run Code Online (Sandbox Code Playgroud)