我正在尝试使用 handlebars.js 创建一个动态表。我想放在表格中的一个对象的例子是:
Object { title: "The Room", director: "Tommy Wiseau", genre: "Drama?", rating: "1"}
Run Code Online (Sandbox Code Playgroud)
我想要的 HTML 如下所示:
<thead>
<th>Title</th>
<th>Director</th>
<th>Genre</th>
<th>Rating</th>
<th>Edited</th>
</thead>
<tbody>
<tr>
<td>The Room</td>
<td>Tommy Wiseau</td>
<td>Drama?</td>
<td>1</td>
<td>2017-05-16</td>
</tr>
</tbody>
Run Code Online (Sandbox Code Playgroud)
我的问题是用户也可以添加他们自己的表头,所以我不能例如只做:
<td>{{title}}</td>
Run Code Online (Sandbox Code Playgroud)
它必须动态完成。我看过: {{#each}},但似乎无法围绕它。另外,如何打印属性名称而不仅仅是对象中的值(就像我想要在表标题中一样)。
<thead>
{{#each data}}
<th>{{@key}}</th><!--property name here-->
{{/each}}
</thead>
<tbody>
{{#each data}}
<tr>
<td>{{this}}</td><!--property value here-->
</tr>
{{/each}}
</tbody>
Run Code Online (Sandbox Code Playgroud)
这是我的模板。我觉得我正在接近正确的解决方案,但我不确定我做错了什么。
$.getJSON("php/loadItems.php?category=" + selected, function(data) {
let source = $("#itemTemplate").html();
let template = Handlebars.compile(source);
delete data[0].id
$("#tableContainer").append(template(data));
});
Run Code Online (Sandbox Code Playgroud)
这就是我在 JS 中处理数据的方式。任何帮助是极大的赞赏!