2015-11-27 31 views
0

我试图用车把解析JavaScript对象,但由于某种原因,把手不能正常加载数据...把手不解析数据

这里是我的模板文件:

{{> header}} 
<h1>Handlebars JS Example</h1> 
<script id="some-template" type="text/x-handlebars-template"> 
<table> 
    <thead> 
     <th>Name</th> 
     <th>Job Title</th> 
     <th>Twitter</th> 
    </thead> 
    <tbody> 
     {{#users}} 
     <tr> 
      <td>{{fullName person}}</td> 
      <td>{{jobTitle}}</td> 
      <td><a href="https://twitter.com/{{twitter}}">@{{twitter}}</a></td> 
     </tr> 
     {{/users}} 
    </tbody> 
</table> 
</script> 
    <body> 
    <!-- Insertion point for handlebars template --> 
     <div id="main" style="margin-left:100px"> 
     </div> 
    </body> 
<script type="text/javascript" src="javascript/templating.js"></script> 

这里是我的.js文件:

$(document).ready(function() { 

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

    var data = { 
     users: [ { 
      person: { 
       firstName: "Garry", 
       lastName: "Finch" 
      }, 
      jobTitle: "Front End Technical Lead", 
      twitter: "gazraa" 
     }, { 
      person: { 
       firstName: "Garrasd", 
       lastName: "Finch" 
      }, 
      jobTitle: "Photographer", 
      twitter: "photobasics" 
     }, { 
      person: { 
       firstName: "Garry", 
       lastName: "Finch" 
      }, 
      jobTitle: "LEGO Geek", 
      twitter: "minifigures" 
     } ] 
    }; 

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

    console.log(template(data)); 

    $("#main").append(template(data)); 

}); 

注 - 当我CONSOLE.LOG(模板(数据)),我得到如下:

<table> 
<thead> 
    <th>Name</th> 
    <th>Job Title</th> 
    <th>Twitter</th> 
</thead> 
<tbody> 
</tbody> 

任何人都知道我在做什么错?我正在使用node.js + express。

谢谢!

回答

0

您没有为users定义任何块助手,但试图在模板中使用它。

更改这些行

... 
{{#users}} 
... 
{{/users}} 
... 

这些:这里

... 
{{#each users}} 
... 
{{/each}} 
... 

退房的文档:http://handlebarsjs.com/builtin_helpers.html#iteration

各区块帮手

您可以使用内置的每个助手遍历列表。在 块内部,您可以使用它来引用正在迭代的元素。

+0

嗨 - 我试过了,但没有运气。请注意 - 上面的示例基于此: http://jsfiddle.net/aybalasubramanian/N2b5M/1/ –