我無法弄清楚如何將從 MySQL 數據庫獲取的數據傳遞到我的 HTML 模板并顯示表格中的每一列。我發現的說明工作正常,但是當我嘗試將它實現到我自己的代碼中時,它不會將數據傳遞到我的 HTML,并且表格仍然是空的。去代碼:var table = NewView("bootstrap", "views/pages/table.gohtml")func main() { http.Handle("/views/", http.StripPrefix("/views/", http.FileServer(http.Dir("./views")))) http.HandleFunc("/table", tableHandler) fmt.Println("server running on port :8080") http.ListenAndServe(":8080", nil)}func tableHandler(w http.ResponseWriter, r *http.Request) { db := ipSQL.SqlConnect() data := ipSQL.SqlSelect(db) // This returns a nested struct and stores it in the 'data' variable. /* type Data struct { Items []Devicevalue_view } type Devicevalue_view struct { Name string Ip string Pcn string Description string } */ fmt.Println(data) //The println prints the following: 'test1: {[{Name1 192.168.166.13 123456 webserver} {Name2 192.168.166.14 123456 webserver2}]}' err := table.Render(w, data) //This renders the page together with a default layout. table is initialized somewhere else in this way: // var table = NewView("bootstrap", "views/pages/table.gohtml") --> This is a function I found and confirmed to be working. if err != nil { panic(err) }}我一直在使用以下代碼從名為 bootstrap.gohtml 的不同文件呈現我的網頁的標準布局,并從我指定的文件中獲取 HTML 的主體。(在 ---UPDATE 2 中添加了這個)func NewView(layout string, files ...string) *View { files = append(layoutFiles(), files...) t, err := template.ParseFiles(files...) if err != nil { panic(err) } return &View{ Template: t, Layout: layout, }}type View struct { Template *template.Template Layout string}func (v *View) Render(w http.ResponseWriter, data interface{}) error { spew.Dump(data) return v.Template.ExecuteTemplate(w, v.Layout, data)}
1 回答

茅侃侃
TA貢獻1842條經驗 獲得超21個贊
我通過將 {{template "yield"}} 更改為 {{template "yield" .}} 使其工作。據我了解,這將使用管道將變量解析到下一個模板文件。
{{define "bootstrap"
<head>some links to css among other things</head>
<nav>a navigation bar</nav>
{{template "yield" .}}
<foot>footer</foot>
{{end}}
yield 模板現在可以訪問我解析到 bootstrap 模板的變量。
- 1 回答
- 0 關注
- 114 瀏覽
添加回答
舉報
0/150
提交
取消