将* datastore.Key添加到切片

I am getting all the data successfully and displayed in a table using template. I am using Go in this code querying the datastore with Membership as entity type.

In the html page, all the data are displayed but not the keys.

I have tried to add Key *datastore.Key as property to the Membership struct but still no luck.

Here is my code:

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>`

You need to assign the key to the Key property:

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]
    }
  ....
}

You might also want to disable storing the Key property in the datastore:

type Membership struct {
    Key *datastore.Key `datastore:"-"`
    ....
}

Btw. if you want to display the *datastore.Key in HTML, you should Encode() it before.