I am using the underscore.js template library with my backbone example. My template looks like this:
<script id="results-template" type="text/template">
<h2><%= title %></h2>
</script>
The JSON object looks like this:
{"src":"placeholder.jpg","title":"an image placeholder","coordinates":[0,0],"tags":["untagged"],"location":"home"}
I am trying to parse this object through my template but the error I get through my console is:
Uncaught ReferenceError: title is not defined
What am I doing wrong? Live fiddle is here: http://jsfiddle.net/amit_e/muLjV/46/
your problem is this:
JSON.stringify(myPhoto)
this needs to be
myPhoto.toJSON()
reason: your JSON.stringify()
will put the whole myPhoto model as a json string. now, Backbone has this function to output json as a json object, so you can use model.toJSON()
updated jsfiddle: http://jsfiddle.net/saelfaer/muLjV/50/
If you want to display only title, it is not required to process whole JSON of Photo model. You can just retrieve the single property.
Below Render will suffice the need here.
render: function(event){
var yourOutput={title:myPhoto.get('title')};
var compiled_template = _.template( $("#results-template").html(),yourOutput);
this.el.html(compiled_template);
}
Your current JSON object is as below. It is not much complex, you can get any of title, src,coordinates,tags, location without effort.
{
"src": "placeholder.jpg",
"title": "an image placeholder",
"coordinates": [0,0],
"tags": ["untagged"],
"location": "home"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With