如何使用Mustache.js按分类ID分组渲染列表并补全缺失ID占位符
解决方案
Mustache 是无逻辑模板引擎,不支持在模板内直接做数据分组、缺失项补全这类运算,所有数据结构调整需要在传入模板前完成,整体实现分三步:
1. 预处理原始数据
先把原始商品按分类ID分组,再补全ID区间内缺失的空分类,最终生成模板可直接遍历的结构化数据:
// 原始商品数据 const rawProducts = [ { "category": 1, "product": "Sugar" }, { "category": 1, "product": "Oil" }, { "category": 2, "product": "Spice" }, { "category": 3, "product": "Salt" }, { "category": 3, "product": "Eggs" }, { "category": 5, "product": "Bread" }, { "category": 5, "product": "Butter" }, { "category": 7, "product": "Milk" } ]; // 按分类ID归集商品 const categoryGroup = {}; rawProducts.forEach(item => { if (!categoryGroup[item.category]) categoryGroup[item.category] = []; categoryGroup[item.category].push(item.product); }); // 补全区间内缺失的空分类 const existCategoryIds = Object.keys(categoryGroup).map(Number); const startId = Math.min(...existCategoryIds); const endId = Math.max(...existCategoryIds); const renderData = { categories: [] }; for (let cid = startId; cid <= endId; cid++) { renderData.categories.push({ id: cid, productList: categoryGroup[cid] || [] }); }
2. 编写Mustache模板
模板直接遍历预处理好的分类数组即可,空分类会自动渲染为空列表:
{{#categories}} <ul id="category-{{id}}"> {{#productList}} <li>{{.}}</li> {{/productList}} </ul> {{/categories}}
3. 执行渲染
传入预处理好的数据调用渲染方法,输出结果完全匹配预期:
// template 为上面定义的模板字符串 const outputHtml = Mustache.render(template, renderData); // 将结果插入页面对应容器即可 document.querySelector('#output').innerHTML = outputHtml;
说明
- 如果需要固定分类ID的起止范围(比如固定要求1-10全部分类都展示),直接修改预处理逻辑里循环的
startId和endId即可,其余代码不用调整。 - 不要尝试在Mustache模板内编写数据处理逻辑,这不符合Mustache的设计约定,也会大幅增加模板维护成本。
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

