I am trying to access the id of this element sent by json in handlebars.js
{
"status":"success",
"message": {
"message":"sdasdasasd",
"type":"photo",
"post_id":55,
"title":"",
"description":"",
"url":"",
"image":"",
"code":"",
"provider":"",
"photo": {
"http:\/\/timeline.dev\/storage\/app\/public\/vdjkelly\/timeline_SzfkoDzMWc.jpg":"http:\/\/timeline.dev\/storage\/app\/public\/vdjkelly\/timeline_SzfkoDzMWc.jpg",
"http:\/\/timeline.dev\/storage\/app\/public\/vdjkelly\/timeline_qm7sq7RY1K.jpg":"http:\/\/timeline.dev\/storage\/app\/public\/vdjkelly\/timeline_qm7sq7RY1K.jpg"
}
}
}
The code I have like this
@{{#each photo}}
<li class="grid">
<div class="posted-photo">
<div class="photo">
<div class="fphoto-item">
<a class="ShowStatus" data-id="@{{post_id}}" href="#" data-lightbox="lightbox@{{post_id}}">
<img src="@{{this}}" class="imgpreview" id="@{{post_id}}" rel="@{{post_id}}">
</a>
</div>
</div>
</li>
@{{/each}}
and still does not access mepost_id
My js code is as follows:
var template = render_template('#send-photo', {
'message': response.message.message,
'type': response.message.type,
'photo': response.message.photo,
'post_id': response.message.post_id
});
Cause: different contexts
The problem happens because you have changed the context and then
post_id
it is no longer accessible.The concept of context in Handlebars/Mustache would be the object whose properties you can access using the curly braces
{{ }}
at a given time. The top level of the context is the object you've passed as the second parameter torender_template
, but helpers like#each
modify it.By doing so
@{{#each photo}}
you are changing the context of the original to exclusively the objectphoto
where there is no longer a property calledpost_id
so it{{post_id}}
is displayed empty.For more information on contexts and paths in the Handlebars documentation .
Solution: change route with
../
In your case you have changed the context to
photo
, so you only want to raise to the parent context. To do this you can use../
to change the path of the property to that of the parent. In your case, what you would have to change is{{post_id}}
to{{../post_id}}
and that will fix the problem.The lines that would need changes in your code: