google app engine - Execute formatted time in a slice with html/template -
i'm making simple webserver can host blog, whatever do; can not execute proper formatted time html/template.
here's do:
i've created struct:
type blogpost struct { title string content string date time.time }
next i've created little func retrieves blogposts corresponding title/dates appengine datastore , return slice:
func getblogs(r *http.request, max int) []blogpost { c := appengine.newcontext(r) q := datastore.newquery("blogpost").order("-date").limit(max) bp := make([]blogpost, 0, max) q.getall(c, &bp) return bp }
finally, in bloghandler create slice based on retrieved data appengine datastore using:
blogs := getblogs(r, 10)
now when execute template called blog this, dates of blogs being parsed default dates:
blog.execute(w, blogs) // gives dates like: 2013-09-03 16:06:48 +0000 utc
so, me, being golang n00b am, function following give me result want
blogs[0].date = blogs[0].date.format("02-01-2006 15:04:05") // return 03-09-2013 16:06:48, @ least when print formatted date is.
however results in type conflict ofcourse, tried solve using:
blogs[0].date, _ = time.parse("02-01-2006 15:04:05", blogs[0].date.format("02-01-2006 15:04:05")) // returns once again: 2013-09-03 16:06:48 +0000 utc
it n00b thing oversaw once again, can't see how can't override time.time type in slice or @ least print in format want.
your date
field has type time.time
. if format string, , parse back, you'll once again time.time
value, still print default way when template execution calls string
method, it's not solving problem.
the way solve providing template formatted time string instead of time value, , can in multiple ways. example:
add method blog post type named
formatteddate
or similar, returns string formatted in style of preference. that's easiest, , nicest way if don't have fancy use case.add string field blog type named
formatteddate
or similar; that's similar above option, have careful set , update field whenever necessary, i'd prefer method option instead.if you'd format time values in multiple ways within template, might opt define template formatter function, might
{{post.date | fdate "02-01-2006 15:04:05"}}
. see documentation on template.funcs, funcmap type, , this example details on how that.
update: sample code first option: http://play.golang.org/p/3qydrdq1yo
Comments
Post a Comment