howtodothis
howtodothis

Reputation: 1305

How to iterate over nested objects using Handlebars

I would like to know how to iterate over the following data object using handlebars.

Here is what it outputs:

image2.png | title2 
image3.png | title3 

What I would like to achieve:

image1.png | title1
image2.png | title2 
image3.png | title3 

Data

var data = {
  "item": [{ // item with one image
      "src" : "image1.png",
      "title" : "title1"
  }],
  "item": [{ // item with two or more images
      "src" : "image2.png",
      "title" : "title2"
  },
  {
      "src" : "image3.png",
      "title" : "title3"
  }]
}

var template = Handlebars.compile($("#data-template").text());
var html = template(data);
$('#placeholder').html(html);

Template

<div id="placeholder"></div>
<script type="text/x-handlebars" id="data-template">
    {{#item}}
       {{src}} | {{title}} <br>
    {{/item}}
</script>

http://jsfiddle.net/88CwB/

Upvotes: 0

Views: 2267

Answers (1)

Shadow Man
Shadow Man

Reputation: 3402

Your JSON is invalid.

Handlebars can only see 2 items.

var data = {
  "item": [{ // item with one image
      "src" : "image1.png",
      "title" : "title1"
  }],
  "item": [{ // item with two or more images
      "src" : "image2.png",
      "title" : "title2"
  },
  {
      "src" : "image3.png",
      "title" : "title3"
  }]
}


var template = Handlebars.compile($("#data-template").text());
var html = template(data);
$('#placeholder').html("<p>" + data.item + "</p>");

See: http://jsfiddle.net/hZQnD/1/

You can fix it by making your data object contain only 1 item object, which may contain an array of 3 items.

var data = {
  "item": [{ // item with 3 images
      "src" : "image1.png",
      "title" : "title1"
  },
  {
      "src" : "image2.png",
      "title" : "title2"
  },
  {
      "src" : "image3.png",
      "title" : "title3"
  }]
}


var template = Handlebars.compile($("#data-template").text());
var html = template(data);
$('#placeholder').html(html);

See: http://jsfiddle.net/75UzZ/1/

You can also fix it by making your data object an array of objects with item properties and iterating through them in a for loop:

var data = [{
    "item": [{ // item with one image
        "src" : "image1.png",
        "title" : "title1"
    }]
  },{
    "item": [{ // item with two or more images
        "src" : "image2.png",
        "title" : "title2"
    },
    {
        "src" : "image3.png",
        "title" : "title3"
    }]
}];

var template = Handlebars.compile($("#data-template").text());
var html = ""
for( var i = 0; i < data.length; ++i ){
  html += template(data[i]);
}
$('#placeholder').html(html);

See: http://jsfiddle.net/dFmQG/2/

Upvotes: 1

Related Questions