这是一个 Example的应用程序。主要代码在: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)。 现在我试着获取最新的博文
// Get the latest blogposts
c := 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 无效,我已经尝试了数千种方法,但没有任何效果:-( )
有人知道吗?这太棒了!
编辑: 我用 mustache 。
在我使用的代码中:
x["Blogposts"] = blogposts
data := mustache.RenderFile("templates/about.mustache", x)
sendData(w, data) // Equivalent to fmt.Fprintf
然后可以使用 {{{Content}}} 或 {{{PostTitle}}} 等在 .mustache 模板中访问数据。
最佳答案
正如 hyperslug 所指出的,实体的 id 字段在键上,而不是它被读入的结构。
解决此问题的另一种方法是将 id 字段添加到您的结构并将数据存储告诉 ignore it ,例如:
type Blogposts struct {
PostTitle string
PostPreview string
Content string
Creator string
Date time.Time
Id int64 `datastore:"-"`
}
然后您可以像这样在调用 GetAll() 之后手动填充 Id 字段
keys, err := q.GetAll(c, &blogposts)
if err != nil {
// handle the error
return
}
for i, key := range keys {
blogposts[i].Id = key.IntID()
}
这样做的好处是不需要引入额外的类型。
关于google-app-engine - Golang GAE - mustache 结构中的 intID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9956342/