0

我很难理解如何使用带有 jQ​​uery 的 handlebars.js 来处理顶级字典数组

我的数据对象不包含带有命名数组对象的字典(这是大多数在线示例处理的内容)。我的数据对象如下所示:

[
  {
    "Type": "TopLevel",
    "Identifier": "123456789IL",
    "FullName": "Smith, John H.",
    "CurrentLocation": "In Building"
  },
  {
    "Type": "TopLevel",
    "Identifier": "123456789OL",
    "FullName": "Doe, Jane M.",
    "CurrentLocation": "Parking Lot"
  }
]

这是一个工作的 jsfiddle(使用命名的数组对象(我没有)和一个非工作的 jsfiddle 与我的实际数据对象(不起作用)。

http://jsfiddle.net/eljaywilson/ZhF5h/ - 有效,但不是我的数据对象的外观

http://jsfiddle.net/eljaywilson/ZhF5h/1/ - 没有工作

4

2 回答 2

2

您的模板中有错误 - 您必须将 [/users] 更改为 {{/.}},如下所示:

    <tbody> 
        {{#.}}
        <tr> 
            <td>{{Type}}</td> 
            <td>{{FullName}}</td> 
            <td>{{CurrentLocation}}</td> 
            <td>{{Identifier}}</td> 
        </tr> 
        {{/.}}
    </tbody> 
于 2013-12-23T15:50:54.933 回答
1

这应该可以解决您的问题:

var source = $("#some-template").html(); 
var template = Handlebars.compile(source); 

var data =  [
  {
    "Type": "TopLevel",
    "Identifier": "123456789IL",
    "FullName": "Smith, John H.",
    "CurrentLocation": "In Building"
  },
  {
    "Type": "TopLevel",
    "Identifier": "123456789OL",
    "FullName": "Doe, Jane M.",
    "CurrentLocation": "Parking Lot"
  }
]
; 

Handlebars.registerHelper('fullName', function(person) {
  return person.firstName + " " + person.lastName;
});

$('#myDiv').append(template({ users: data }));

解释:

data 是一个数组,您只需在传递给模板之前将其包装起来。

固定 jsfiddle 在这里:http: //jsfiddle.net/akhikhl/bTzf3/1/

于 2013-12-23T15:50:19.510 回答