转到html模板表

时间:2019-07-07 15:24:11

标签: html loops templates go

我想在go包“ 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
...

我不理解如何连接一张桌子中的所有单元格

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

1 个答案:

答案 0 :(得分:2)

因为您正在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>