Question

Does handlebarsjs work with the JSONObject? I have an object of arrays that comes from the db in php, it is always a std object.

php,

$items = std object

echo json_encode($items);

result,

{"items":{"0":{"pub_name":"Main","system_id":"50","make_accessible":"0","count":"19","router":"#!page\/main\/list\/"},"1":{"pub_name":"estate","system_id":"122","make_accessible":"0","count":"8","router":null},"2":{"pub_name":"wines","system_id":"125","make_accessible":"0","count":"5","router":null},"3":{"pub_name":"visits","system_id":"128","make_accessible":"0","count":"4","router":null},"4":{"pub_name":"community","system_id":"131","make_accessible":"0","count":"8","router":null},"5":{"pub_name":"events","system_id":"137","make_accessible":"0","count":"8","router":null},"6":{"pub_name":"Contact","system_id":"140","make_accessible":"0","count":"3","router":null},"7":{"pub_name":"Newsletter","system_id":"143","make_accessible":"0","count":"2","router":null},"8":{"pub_name":"gallery","system_id":"146","make_accessible":"0","count":"2","router":null},"9":{"pub_name":"Discover Our Wines","system_id":"163","make_accessible":"0","count":"2","router":null}},"total":10}

jquery,

$.ajax({
  type:       "GET",
  dataType:   "json",
  url: "server.php"

}).done(function(returndata) {

$(this).html(Handlebars.getTemplate('page')({pages: returndata}));

...

returndata,

Object { items={...}, total=10}

handlebars' template,

{{ pages.items.length }}

result,

empty

What should I do so handlebars templates can read JSONObjects?

Was it helpful?

Solution

Objects do not have a length property, so there is nothing for Handlebars to render.

http://jsfiddle.net/WARUa/ :

var myObject = {items: {0: {k: 1}, 1: {k: 2}}};

var myArray = [{k: 1}, {k: 2}];

alert(myObject.items.length); // undefined
alert(myArray.length); // 2

I would suggest that you adjust the code which returns the JSON, so that items is an array instead.

Alternatively, you'll need something like this: Length of a JavaScript object

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top