How to output a JSON object using underscore.js?

I am using the underscore.js template library with my basic example. My template looks like this:

<script id="results-template" type="text/template"> <h2><%= title %></h2> </script> 

The JSON object is as follows:

 {"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 scene here: http://jsfiddle.net/amit_e/muLjV/46/

+4
source share
2 answers

Your problem is this:

 JSON.stringify(myPhoto) 

it should be

 myPhoto.toJSON() 
Cause

: your JSON.stringify() will put the whole myPhoto model in 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/

+8
source

If you want to display only the title, there is no need to process the entire JSON Photo model. You can just get one property.

A lower render will be quite necessary.

 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 shown below. It is not so difficult, you can get any names, src, coordinates, tags, location without effort.

 { "src": "placeholder.jpg", "title": "an image placeholder", "coordinates": [0,0], "tags": ["untagged"], "location": "home" } 
+1
source

Source: https://habr.com/ru/post/1389227/


All Articles