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.
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.
AFAICS, the
Blogposts
struct has no fieldintID
, but it has a fieldPostTitle
. I guess that could be the reason why the former doesn't and the later does get rendered, though I've never used Mustache...I know this question is a couple years old, but the following article was very helpful to me in this regard: Golang basics with Google Datastore.
In the article, the author provides a nice example of how you can run a query that gets an entity by its ID...
...as well as getting a list/collection of entities with their associated ID:
The snippet above is very close to the helpful answer by @koz.
intID
is an internal property of a Key not the struct, and is accessible through a getter:GetAll
returns[]*Key
, which you're not using: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):
As hyperslug pointed out, the id field of an entity is on the key, not the struct it gets read into.
Another way around this is to add an id field to your struct and tell datastore to ignore it, eg:
You can then populate the Id field manually after a call to GetAll() like so
This has the benefit of not introducing an extra type.