1

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?

Run
  • 54,938
  • 169
  • 450
  • 748
  • Object { items={...}, so pages.items is an Object?? Just console.log(returndata) and see what really it is. – Andrew Dec 23 '13 at 09:21
  • If items is an object then it has no length property. You'll need something like this: http://stackoverflow.com/questions/5223/length-of-javascript-object-ie-associative-array – bcmcfc Dec 23 '13 at 09:25
  • @ andrew: it is this I get `Object { items={...}, total=10}`. – Run Dec 23 '13 at 09:45
  • and items are `Object { 0={...}, 1={...}, 2={...}, more...}`. – Run Dec 23 '13 at 09:46

1 Answers1

1

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

Community
  • 1
  • 1
bcmcfc
  • 25,966
  • 29
  • 109
  • 181