gpt4 book ai didi

javascript - 如何在 Handlebars/Ember.js 中插入动态 {{property}}?

转载 作者:可可西里 更新时间:2023-11-01 02:44:58 24 4
gpt4 key购买 nike

假设我在 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 类中的每个字段,为它创建一个 header ,然后为每个用户呈现值:

<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: '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>

这将解决您在 handlebar JS 中使用助手的问题

关于javascript - 如何在 Handlebars/Ember.js 中插入动态 {{property}}?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10713559/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com