Kaz*_*ura 6 html javascript handlebars.js
我正在尝试使用 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 中处理数据的方式。任何帮助是极大的赞赏!
根据您所描述的内容,我认为您别无选择,只能通过迭代数组中的每个对象并过滤掉所有重复项来构建表头(对象键)数组。换句话说,您必须从所有数据对象构建一个包含所有唯一键的数组,这些键将用作表中的列标题。您可以使用现有的库来帮助您执行此操作,例如Underscore 的.uniq,但我将提供一个示例实现:
var uniqueKeys = data.reduce(function (acc, obj) {
return acc.concat(Object.keys(obj).filter(key => acc.indexOf(key) === -1));
}, []);
Run Code Online (Sandbox Code Playgroud)
接下来,我们必须将我们的唯一键数组传递给我们的模板。独特的键将被用来创建表格标题,以及在查找操作中每个对象data。
template({
uniqueKeys: uniqueKeys,
data: data
});
Run Code Online (Sandbox Code Playgroud)
我们的模板必须更新为以下内容:
<thead>
<tr>
{{#each uniqueKeys}}
<th>{{this}}</th>
{{/each}}
</tr>
</thead>
<tbody>
{{#each data}}
<tr>
{{#each ../uniqueKeys}}
<td>{{lookup .. this}}</td>
{{/each}}
</tr>
{{/each}}
</tbody>
Run Code Online (Sandbox Code Playgroud)
请注意,该行{{lookup .. this}}是说,“data在具有此键名称的属性中呈现当前对象上的值uniqueKeys。
另请注意,我<tr>在您的<thead>. 根据MDN,这些是<thead>.
我创建了一个小提琴以供参考。
像这样的事情对你想要完成的事情有用吗?
{
"titles": [
"The Room",
"Test"
],
"tableObjs": [{
"director": "Tommy Wiseau",
"genre": "Drama?",
"rating": "1"
},
{
"director": "Tommy Wiseau",
"genre": "Drama?",
"rating": "1"
}
]
}Run Code Online (Sandbox Code Playgroud)
<thead>
{{#each titles}}
<th>{{@key}}</th>
<!--property name here-->
{{/each}}
</thead>
<tbody>
{{#each tableObjs}}
<tr>
<td>{{this.director}}</td>
<td>{{this.genre}}</td>
<td>{{this.rating}}</td>
<!--property value here-->
</tr>
{{/each}}
</tbody>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12991 次 |
| 最近记录: |