模板无法评估类型 Y 中的字段 X
Template can't evaluate field X in type Y
在 Go 中,我循环查询结果并将结果附加到一个切片中。然后我尝试在 html 模板中显示数据,但是我不断收到此错误:executing "orders.html" at <.Customer>: can't evaluate field Customer in type []main.Order
这是我的代码:
type Order struct {
Order_id int
Customer string
Date_of_purchase string
}
func OrderPage(w http.ResponseWriter, r *http.Request) {
db := dbConnection()
var (
order_id int
customer string
date_of_p string
ps []Order
)
rows, err := db.Query("SELECT * FROM orders WHERE customer = 'David'")
if err != nil {
panic(err.Error())
}
for rows.Next() {
err = rows.Scan(&order_id, &customer, &date_of_p)
if err != nil {
log.Println(err)
http.Error(w, "there was an error", http.StatusInternalServerError)
return
}
ps = append(ps, Order{Order_id: order_id, Customer: customer, Date_of_purchase: date_of_p})
}
temp, err := template.ParseFiles("templates/orders.html")
if err != nil {
log.Print("template parsing error: ", err)
}
err = temp.Execute(w, ps)
if err != nil {
fmt.Println(err)
}
}
我的 html 模板如下所示:
<h1>Hello</h1>
<h3>Your username is {{ .Customer }}</h3>
{{ range . }}
<h2> {{ .Order_id }}</h2>
{{ end }}
我从数据库中获取数据,只是无法在 html 页面上显示。
您正在将 ps
的一部分 main.Order
传递给您的模板。在您的模板中,.
仍然是切片。
您的线路 <h3>Your username is {{ .Customer }}</h3>
试图访问此 []main.Order
的成员 Customer
- 它没有。
您可能想从切片的第一个元素中获取客户名称,或者将结构传递给具有此字段的模板,例如像这样:
type Customer struct {
Orders []Order
Username string
}
那么您需要像这样更改您的模板:
<h1>Hello</h1>
<h3>Your username is {{ .Username }}</h3>
{{ range .Orders }}
<h2> {{ .Order_id }}</h2>
{{ end }}
在 Go 中,我循环查询结果并将结果附加到一个切片中。然后我尝试在 html 模板中显示数据,但是我不断收到此错误:executing "orders.html" at <.Customer>: can't evaluate field Customer in type []main.Order
这是我的代码:
type Order struct {
Order_id int
Customer string
Date_of_purchase string
}
func OrderPage(w http.ResponseWriter, r *http.Request) {
db := dbConnection()
var (
order_id int
customer string
date_of_p string
ps []Order
)
rows, err := db.Query("SELECT * FROM orders WHERE customer = 'David'")
if err != nil {
panic(err.Error())
}
for rows.Next() {
err = rows.Scan(&order_id, &customer, &date_of_p)
if err != nil {
log.Println(err)
http.Error(w, "there was an error", http.StatusInternalServerError)
return
}
ps = append(ps, Order{Order_id: order_id, Customer: customer, Date_of_purchase: date_of_p})
}
temp, err := template.ParseFiles("templates/orders.html")
if err != nil {
log.Print("template parsing error: ", err)
}
err = temp.Execute(w, ps)
if err != nil {
fmt.Println(err)
}
}
我的 html 模板如下所示:
<h1>Hello</h1>
<h3>Your username is {{ .Customer }}</h3>
{{ range . }}
<h2> {{ .Order_id }}</h2>
{{ end }}
我从数据库中获取数据,只是无法在 html 页面上显示。
您正在将 ps
的一部分 main.Order
传递给您的模板。在您的模板中,.
仍然是切片。
您的线路 <h3>Your username is {{ .Customer }}</h3>
试图访问此 []main.Order
的成员 Customer
- 它没有。
您可能想从切片的第一个元素中获取客户名称,或者将结构传递给具有此字段的模板,例如像这样:
type Customer struct {
Orders []Order
Username string
}
那么您需要像这样更改您的模板:
<h1>Hello</h1>
<h3>Your username is {{ .Username }}</h3>
{{ range .Orders }}
<h2> {{ .Order_id }}</h2>
{{ end }}