亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang GAE-胡子中struct的intID

Golang GAE-胡子中struct的intID

Go
呼啦一陣風 2021-04-29 14:12:07
這是該應用程序的示例?;敬a在:golang-code / handler / handler.go中(在主題之后應顯示一個ID!)我試圖在Google Appengine上的Golang中建立一個小型博客系統,并使用Mustache作為模板引擎。所以,我有一個結構:type Blogposts struct {    PostTitle   string    PostPreview string    Content     string    Creator     string    Date        time.Time}數據通過傳遞給GAE    datastore.Put(c, datastore.NewIncompleteKey(c, "Blogposts", nil), &blogposts)因此,GAE自動分配一個intID(int64)?,F在我試圖獲得最新的博客文章// Get the latest blogpostsc := appengine.NewContext(r)q := datastore.NewQuery("Blogposts").Order("-Date").Limit(10)var blogposts []Blogposts_, err := q.GetAll(c, &blogposts)直到那里一切正常,但是當我嘗試訪問intID(或stringID,無論如何)時,我無權訪問此:-(<h3><a href="/blog/read/{{{intID}}}">{{{PostTitle}}}</a></h3>(PostTitle起作用,intID不起作用,我已經嘗試了數千種東西,沒有任何作用:-()有人有主意嗎?太好了!編輯:我用胡子。http://mustache.github.com/在代碼中,我使用:x["Blogposts"] = blogpostsdata := mustache.RenderFile("templates/about.mustache", x)sendData(w, data) // Equivalent to fmt.Fprintf然后可以使用{{{Content}}}或{{{PostTitle}}}等在.mustache模板中訪問數據。
查看完整描述

3 回答

?
小唯快跑啊

TA貢獻1863條經驗 獲得超2個贊

intID 是Key的內部屬性,而不是struct,可以通過getter進行訪問:


id := key.IntID()

GetAll返回[]*Key,您沒有使用它:


_, err := q.GetAll(c, &blogposts)

解決此問題的一種方法是創建一個既包含帖子信息又包含關鍵信息的viewmodel結構(未經測試,但這是要點):


  //... handler code ...


  keys, err := q.GetAll(c, &blogposts)

  if err != nil {

    http.Error(w, "Problem fetching posts.", http.StatusInternalServerError)

    return

  }


  models := make([]BlogPostVM, len(blogposts))

  for i := 0; i < len(blogposts); i++ {

    models[i].Id = keys[i].IntID()

    models[i].Title = blogposts[i].Title

    models[i].Content = blogposts[i].Content

  }


  //... render with mustache ...

}


type BlogPostVM struct {

  Id int

  Title string

  Content string

}


查看完整回答
反對 回復 2021-05-10
  • 3 回答
  • 0 關注
  • 211 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號