如何使用Handlebars迭代嵌套对象

时间:2013-05-30 23:53:28

标签: javascript json handlebars.js

我想知道如何使用把手迭代以下数据对象。

以下是它的输出:

image2.png | title2 
image3.png | title3 

我想要实现的目标:

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

数据

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);

模板

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

http://jsfiddle.net/88CwB/

1 个答案:

答案 0 :(得分:1)

您的JSON无效。

把手只能看到2件物品。

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>");

请参阅:http://jsfiddle.net/hZQnD/1/

您可以通过使data对象仅包含1个item对象来修复它,该对象可能包含3个项目的数组。

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);

请参阅:http://jsfiddle.net/75UzZ/1/

您还可以通过使数据对象成为具有item属性的对象数组并在for循环中迭代它们来修复它:

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);

请参阅:http://jsfiddle.net/dFmQG/2/