说我在
JavaScript中有一个用户模型,看起来像这样:
var User = function(attributes) { this.attributes = attributes; } User.fields = [ {name: 'firstName'},{name: 'lastName'},{name: 'email'} ] User.prototype.get = function(key) { return this.attributes[key]; } User.all = [new User({firstName: 'Foo'})];
而且我想通过一个Handlebars模板来运行它,该模板遍历User类的每个字段,为它创建一个头,然后为每个用户渲染值:
<table> <thead> <tr> {{#each User.fields}} <th>{{name}}</th> {{/each}} </tr> </thead> <tbody> {{#each User.all}} <tr> {{#each User.fields}} <td>{{content.get(name)}}</td> {{/each}} </tr> {{/each}} </tbody> </table>
我的问题是,如何完成内部部分:
{{#each User.fields}} <td>{{content.get(name)}}</td> {{/each}}
这基本上是用user.get(field.name).在Handlebars中,我怎么能做到这一点,因为我不知道手头之前的领域,并希望这是动态的?
谢谢你的帮助.
解决方法
<body> <div id='displayArea'></div> <script id="template" type="text/x-handlebars-template"> <table border="2"> <thead> <tr> {{#each Fields}} <th>{{name}}</th> {{/each}} </tr> </thead> <tbody> {{#each users}} <tr> {{#each ../Fields}} <td>{{getName name ../this}}</td> {{/each}} </tr> {{/each}} </tbody> </table> </script> <script type="text/javascript"> var User = function(attributes) { this.attributes = attributes; } User.fields = [ {name: 'firstName'},{name: 'email'} ] User.prototype.get = function(key) { return this.attributes[key]; } User.all = [new User({firstName: 'Foo',lastName :'ooF',email : 'foo@gmail.com'}),new User({firstName: 'Foo2'})]; //array of user //handle bar functions to display $(function(){ var template = Handlebars.compile($('#template').html()); Handlebars.registerHelper('getName',function(name,context){ return context.get(name); }); $('#displayArea').html(template({Fields :User.fields,users:User.all})); }); </script> </body>
这将解决使用助手在工具栏JS中的问题