假设我在JavaScript中有User
模型,看起来像这样:
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中做到这一点,因为我不知道前面的字段并希望它是动态的?
感谢您的帮助。
答案 0 :(得分:8)
<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: 'lastName'},
{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中使用助手的问题
答案 1 :(得分:-3)
您可以编写一个Handlebars帮助程序来为您执行此操作。