我正在成功获取所有数据,并使用模板将其显示在表格中。我在此代码中使用Go查询以Membership作为实体类型的数据存储。在html页面中,显示所有数据,但不显示键。我试图添加Key *datastore.Key作为属性的Membership结构,但仍然没有运气。这是我的代码:package helloimport ( "appengine" "appengine/datastore" "html/template" "net/http" "time") type Membership struct { Key *datastore.Key Author string Content string FirstName string LastName string Address string Email string Grade string Date time.Time}func init() { http.HandleFunc("/", members)}func members(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) q := datastore.NewQuery("Membership").Order("-Date") memberships := make([]Membership, 0, 10) if _, err := q.GetAll(c, &memberships); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if err := membersTemplate.Execute(w, memberships); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) }}var membersTemplate = template.Must(template.New("page").Parse(membersTemplateHTML))const membersTemplateHTML = `<html> <body> <table><tr><th>Key</th><th>Name</th><th>Email</th><th>Adress</th><th>Grade</th></tr> {{range .}} <tr> <td>{{.Key}}</td> <td>{{.FirstName}} {{.LastName}}</td> <td>{{.Email}}</td> <td>{{.Address}}</td> <td>{{.Grade}}</td> </tr> {{end}} </table> </body></html>`
1 回答
拉莫斯之舞
TA贡献1820条经验 获得超10个赞
您需要将密钥分配给Key属性:
func members(w http.ResponseWriter, r *http.Request) {
....
if keys, err := q.GetAll(c, &memberships); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Loop over the membership and add the keys
for i := range memberships {
memberships[i].Key = keys[i]
}
....
}
您可能还想禁用将Key属性存储在数据存储中:
type Membership struct {
Key *datastore.Key `datastore:"-"`
....
}
顺便提一句。如果要以*datastore.KeyHTML格式显示,则应Encode()先显示。
- 1 回答
- 0 关注
- 169 浏览
添加回答
举报
0/150
提交
取消