Tes*_*ser 6 google-app-engine go mustache google-cloud-datastore
这是应用程序的示例.基本代码在:golang-code/handler/handler.go(主题应该出现一个ID!)
我试图在Google Appengine上的Golang中构建一个小博客系统,并使用Mustache作为模板引擎.
所以,我有一个结构:
type Blogposts struct {
PostTitle string
PostPreview string
Content string
Creator string
Date time.Time
}
Run Code Online (Sandbox Code Playgroud)
数据通过GAE传递给GAE
datastore.Put(c, datastore.NewIncompleteKey(c, "Blogposts", nil), &blogposts)
Run Code Online (Sandbox Code Playgroud)
因此,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)
Run Code Online (Sandbox Code Playgroud)
直到所有的东西都工作正常,但当我尝试访问intID(或stringID,无论如何),我没有访问权限:-(
<h3><a href="/blog/read/{{{intID}}}">{{{PostTitle}}}</a></h3>
Run Code Online (Sandbox Code Playgroud)
(PostTitle有效,intID没有,我已经尝试了数千件事,没有任何效果:-()
有人有想法吗?这太好了!
编辑:我用小胡子.
在我使用的代码中:
x["Blogposts"] = blogposts
data := mustache.RenderFile("templates/about.mustache", x)
sendData(w, data) // Equivalent to fmt.Fprintf
Run Code Online (Sandbox Code Playgroud)
然后可以使用{{{Content}}}或{{{PostTitle}}}等在.mustache模板中访问数据.
小智 15
正如hyperslug指出的那样,实体的id字段在键上,而不是它被读入的结构.
另一种方法是在结构中添加一个id字段,并告诉数据存储区忽略它,例如:
type Blogposts struct {
PostTitle string
PostPreview string
Content string
Creator string
Date time.Time
Id int64 `datastore:"-"`
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以在调用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()
}
Run Code Online (Sandbox Code Playgroud)
这样做的好处是不引入额外的类型.
intID 是Key而不是struct的内部属性,可以通过getter访问:
id := key.IntID()
Run Code Online (Sandbox Code Playgroud)
GetAll返回[]*Key,你没有使用:
_, err := q.GetAll(c, &blogposts)
Run Code Online (Sandbox Code Playgroud)
解决这个问题的一种方法是创建一个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
}
Run Code Online (Sandbox Code Playgroud)