duanduo3712 2012-03-31 13:37
浏览 48
已采纳

Golang GAE-胡子的结构中的intID

Here is an Example of the app. The essential code is in: golang-code/handler/handler.go (After the subject should appear an ID!)

Im trying to build a little blog system in Golang on Google Appengine and use Mustache as template engine.

So, i have a struct:

type Blogposts struct {
    PostTitle   string
    PostPreview string
    Content     string
    Creator     string
    Date        time.Time
}

The data is passed to GAE via

    datastore.Put(c, datastore.NewIncompleteKey(c, "Blogposts", nil), &blogposts)

So, GAE assigns automatically a intID (int64). Now I tried to get the latest blogposts

// Get the latest blogposts
c := appengine.NewContext(r)
q := datastore.NewQuery("Blogposts").Order("-Date").Limit(10)

var blogposts []Blogposts
_, err := q.GetAll(c, &blogposts)

Until there all things works fine, but when I try to access intID (or stringID, whatever) I dont have access to this :-(

<h3><a href="/blog/read/{{{intID}}}">{{{PostTitle}}}</a></h3>

(PostTitle works, intID not, i've tried thousand of things, nothing worked :-( )

Anyone an idea? This would be great!

Edit: I use mustache.

http://mustache.github.com/

In the code I use:

x["Blogposts"] = blogposts
data := mustache.RenderFile("templates/about.mustache", x)
sendData(w, data) // Equivalent to fmt.Fprintf

And then the data can be accessed in the .mustache template with {{{Content}}} or {{{PostTitle}}} etc.

  • 写回答

4条回答 默认 最新

  • doumu4032 2012-03-31 22:57
    关注

    intID is an internal property of a Key not the struct, and is accessible through a getter:

    id := key.IntID()
    

    GetAll returns []*Key, which you're not using:

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

    One way to get around this is to create a viewmodel struct that has both your post and key info (untested, but this is the gist of it):

      //... 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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器