google-app-engine - Golang GAE - mustache 结构中的 intID

标签 google-app-engine google-cloud-datastore go mustache

这是一个 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 。

http://mustache.github.com/

在我使用的代码中:

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/

相关文章:

sockets - 从所有端口监听

去 Gin : Creating generic custom validators

python - Google App Engine 中的 key 生成

google-app-engine - 请求特定网址时 App Engine 中的 DownloadError

python - 从本地 GAE 项目连接到 Google Cloud Datastore

java - GAE (Java) 高复制数据存储测试 - 测试用例之间未清除数据存储

google-app-engine - google appengine golang API - InstanceClass

google-app-engine - Google App Engine 和键值存储

java - Objectify 是否支持 Joda-Time Interval 类?

Go Template 范围内的额外行