我有以下JavaScript对象:
{
"categories": [{
"name": "cat0",
"position": 0
}, {
"name": "cat1",
"position": 1
}, {
"name": "cat2",
"position": 2
}
],
"series": [{
"name": "ser0",
"position": 0,
"points": [{
"id": 114,
"name": "ser0cat0",
"position": 0
}, {
"id": 82,
"name": "ser0cat1",
"position": 1
}
]
}, {
"name": "ser1",
"position": 1,
"points": [{
"id": 81,
"name": "ser1cat1",
"position": 1
}, {
"id": 82,
"name": "ser1cat2",
"position": 2
}
]
}, {
"name": "ser2",
"position": 2,
"points": [{
"id": 83,
"name": "ser2cat0",
"position": 0
}
]
}, {
"name": "ser3",
"position": 3,
"points": [{
"id": 82,
"name": "ser3cat0",
"position": 0
}
]
}
]
}
如图所示,categories
,series
和points
都具有定义的位置属性,但是每个类别/系列交点不一定都有点。我希望创建一个HTML表,其中标题列为类别名称,每行的第一列为系列名称,每行的其余列为点名称(如果存在点)或“空”(例如)如下:
我的困难是每列不一定都有给定的点,如果有的话,我可以简单地使用{{#each this.points}}<td><a href="javascript:void(0)" class="hb_point" data-id="{{this.id}}">{{this.name}}</a></td>{{/each}}
。相反,我(认为)我需要遍历每个正文行的categories
并使用索引来确定给定单元格是否存在点。
我的尝试在下面,但是会导致{description: undefined, fileName: undefined, lineNumber: 31, message: "each doesn't match ifeq - 31:7", name: "Error", …}
异常。
如何使用Handlebars.js完成此操作?
编辑。也许最好在发送给车把之前遍历对象,并根据需要添加空点对象?实现了它,就可以了。
Handlebars.registerHelper('ifeq', function (a, b, options) {
if (a == b) { return options.fn(this); }
return options.inverse(this);
});
Handlebars.registerHelper('ifnoteq', function (a, b, options) {
if (a != b) { return options.fn(this); }
return options.inverse(this);
});
<table class='tabledragger table' id="chartListCategory">
<thead>
<tr>
<th></th>
{{#each categories}}
<th><a href="javascript:void(0)" class="hb_category">{{this.name}}</a><img alt="Delete Category" src="delete.png" title="Delete Category" class="vtip deleteCategory" height="16" width="16"></th>
{{/each}}
</tr>
</thead>
<tbody>
{{#each series}}
<tr>
<td><a href="javascript:void(0)" class="hb_series">{{this.name}}</a><img alt="Delete Series" src="delete.png" title="Delete Series" class="vtip deleteSeries" height="16" width="16"></td>
{{#each this.categories as |value key|}}
{#ifeq points.key.position value.position}}
<td><a href="javascript:void(0)" class="hb_point" data-id="{{points.key.id}}">{{points.key.name}}</a></td>
{{/ifeq}}
{#ifnoteq points.key.position value.position}}
<td>Empty</td>
{{/ifnoteq}}
{{/each}}
</tr>
{{/each}}
</tbody>
</table>
</script>