[英]how do I use and set custom variables from within a Handlebars.js block?
所以让我们说我有这个 json
food = [
{
name: "banana",
type: "fruit",
color: "yellow"
},
{
name: "apple",
type: "fruit",
color: red"
},
{
name: "strawberry",
type: "fruit",
color: "red"
},
{
name: "carrot",
type: "vegetable",
color: "orange"
},
{
name: "chocolate",
type: "dessert",
color: "brown"
}
]
我想在这样的表格中显示它:
<table>
<thead>
<tr>
<th>Name</th>
<th>Color</th>
</tr>
</thead>
<tbody>
{{#each food}
{{#if lastType == "" or lastType != type}}
<tr>
<td colspan="2">{{type}}
</tr>
{{/if}}
<tr>
<td>{{name}}</td>
<td>{{Color}}</td>
</tr>
{{/each}}
</tbody>
</table>
但是我想在每次有一个新的 type 属性值时添加另一个表行。 所以基本上finally表看起来像这样:
<table>
<thead>
<tr>
<th>Name</th>
<th>Color</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="2">fruit</td>
</tr>
<tr>
<td>banana</td>
<td>yellow</td>
</tr>
<tr>
<td>apple</td>
<td>red</td>
</tr>
<tr>
<td>strawberry</td>
<td>red</td>
</tr>
<tr>
<td colspan="2">vegetable</td>
</tr>
<tr>
<td>banana</td>
<td>yellow</td>
</tr>
<tr>
<td colspan="2">dessert</td>
</tr>
<tr>
<td>chocolate</td>
<td>brown</td>
</tr>
</tbody>
</table>
我怎么能做到这样的事情?
您的目标是将您的食物分组显示,并将类型作为组的标题。 我建议不要将进行这种分组的逻辑放在模板中,因为这很难实现。 更好的解决方案 - 可以保持模板干净整洁 - 是在将数据发送到模板之前对数据进行分组。
理想的数据结构应该是按类型索引食物。 我们可以用一个像下面这样的对象来实现这一点:
{
"fruit": [
{
"color": "yellow",
"name": "banana",
"type": "fruit"
},
{
"color": "red",
"name": "apple",
"type": "fruit"
}
],
"vegetable": [
{
"color": "orange",
"name": "carrot",
"type": "vegetable"
}
],
"dessert": [
{
"color": "brown"
"name": "chocolate",
"type": "dessert"
}
]
}
使用这种数据结构,使用嵌套的{{#each}}
块在我们的模板中获取分组会很简单。 (我假设我们已经将对象命名为“foodsByType”)
{{#each foodsByType}}
<tr>
<td colspan="2">{{@key}}</td>
</tr>
{{#each this}}
<tr>
<td>{{name}}</td>
<td>{{color}}</td>
</tr>
{{/each}}
{{/each}}
如果您正在寻找一种构建foodsByType
对象的好方法,您可以考虑使用Array.prototype.reduce :
const foodsByType = food.reduce((acc, foodItem) => {
if (!acc[foodItem.type]) {
acc[foodItem.type] = [];
}
acc[foodItem.type].push(foodItem);
return acc;
}, {});
我已经创建了一个小提琴供您参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.