将* datastore.Key添加到切片

我正在成功获取所有数据,并使用模板将其显示在表格中。我在此代码中使用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>`


慕尼黑8549860
浏览 170回答 1
1回答

拉莫斯之舞

您需要将密钥分配给Key属性:func members(w http.ResponseWriter, r *http.Request) {&nbsp; ....&nbsp; &nbsp; if keys, err := q.GetAll(c, &memberships); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; http.Error(w, err.Error(), http.StatusInternalServerError)&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; // Loop over the membership and add the keys&nbsp; &nbsp; for i := range memberships {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;memberships[i].Key = keys[i]&nbsp; &nbsp; }&nbsp; ....}您可能还想禁用将Key属性存储在数据存储中:type Membership struct {&nbsp; &nbsp; Key *datastore.Key `datastore:"-"`&nbsp; &nbsp; ....}顺便提一句。如果要以*datastore.KeyHTML格式显示,则应Encode()先显示。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go