I would much appreciate some help on rendering a JSON object on client-side from a Google App Engine entity.
Here is all of my relevant code:
def render_str(template, **params):
t = jinja_env.get_template(template)
return t.render(params)
class BlogHandler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
def render_str(self, template, **params):
params['user'] = self.user
return render_str(template, **params)
def render(self, template, **kw):
self.write(self.render_str(template, **kw))
class Post(ndb.Model):
subject = ndb.TextProperty(required = True)
created = ndb.DateTimeProperty(auto_now_add = True)
startdate = ndb.DateTimeProperty()
enddate = ndb.DateTimeProperty()
class PostPage(BlogHandler):
def get(self, post_id):
key = ndb.Key('Post', int(post_id), parent=blog_key())
post = key.get()
postdict = post.to_dict()
postdict['startdate'] = postdict['startdate'].isoformat()
self.render("permalink.html", postdict = postdict)
In my script tag on the template page, I include
<script>
var jsonobject = JSON.parse({{ postdict['startdate']}});
var jsonobject1 = new Date(jsonobject);
</script>
Am I on the right track here? I would like to ultimately use the datetime object on the client-side for some Jquery functions.
Any help in pointing me in the right direction would be much appreciated.
答案 0 :(得分:1)
There are a number of problems with your code. First of all, once you convert post
to a dictionary postdict
, you can't reference the elements with the dot notation. You have to use a dictionary reference postdict['startdate']
to reference the startdate
element.
Next, I use the isoformat()
function when storing a date in JSON format:
postdict['startdate'] = postdict['startdate'].isoformat()
This makes it easier to convert to a Javascript Date object:
<script>
var jsonobject = JSON.parse({{ postdict.jsonobject}});
jsonobject[0].y = new Date(jsonobject[0].y);
</script>