2

我成功获取所有数据并使用模板显示在表格中。我在此代码中使用 Go 查询以 Membership 作为实体类型的数据存储。

在 html 页面中,所有数据都显示,但不显示键。

我试图将Key *datastore.Key属性添加到Membership结构中,但仍然没有运气。

这是我的代码:

package hello

import (
    "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>`
4

1 回答 1

3

您需要将密钥分配给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.Key在 HTML 中显示,你应该Encode()在之前。

于 2013-01-04T20:56:08.907 回答