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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度