duanba4254 2013-01-04 20:44
浏览 31
已采纳

将* 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>`
  • 写回答

1条回答 默认 最新

  • dou4381 2013-01-04 20:56
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗