Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I output a JSON object with underscore.js?

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/

like image 540
Amit Erandole Avatar asked Jan 18 '23 21:01

Amit Erandole


2 Answers

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/

like image 125
Sander Avatar answered Jan 29 '23 02:01

Sander


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"
}
like image 27
Umesh Patil Avatar answered Jan 29 '23 03:01

Umesh Patil