Amit Erandole
Amit Erandole

Reputation: 12281

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/

Upvotes: 4

Views: 22283

Answers (2)

Umesh Patil
Umesh Patil

Reputation: 10695

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"
}

Upvotes: 1

Sander
Sander

Reputation: 13431

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/

Upvotes: 8

Related Questions