如何使用嵌套字典数据创建Handlebars HTML模板
解决方案
基于现有数据结构的实现
假设你的原始数据结构如下(模拟示例):
const alerts = { Services: { "App A": { "Connection Error": [ { message: "无法连接到数据库", timestamp: "2024-05-20 10:30" }, { message: "API响应超时", timestamp: "2024-05-20 10:45" } ], "Resource Limit": [ { message: "内存使用率达90%", timestamp: "2024-05-20 11:00" } ] }, "App B": { "Service Down": [ { message: "支付服务停止响应", timestamp: "2024-05-20 09:15" } ] } }, Requests: { "App C": { "High Error Rate": [ { message: "POST /login 错误率达30%", timestamp: "2024-05-20 12:00" } ] } } };
要生成符合需求的HTML表格,可通过嵌套遍历数据结构构建内容:
function generateAlertTable(alerts) { let html = '<table border="1" cellpadding="8" cellspacing="0">'; // 构建表头 html += '<thead><tr><th>告警分类</th><th>应用名称</th><th>告警类型</th><th>告警消息</th><th>时间戳</th></tr></thead><tbody>'; // 遍历顶层告警分类(Services/Requests) for (const category in alerts) { const apps = alerts[category]; // 遍历每个应用 for (const appName in apps) { const alertTypes = apps[appName]; // 遍历每个告警类型 for (const alertType in alertTypes) { const alertItems = alertTypes[alertType]; // 遍历每条告警消息并生成表格行 alertItems.forEach(item => { html += `<tr> <td>${category}</td> <td>${appName}</td> <td>${alertType}</td> <td>${item.message}</td> <td>${item.timestamp}</td> </tr>`; }); } } } html += '</tbody></table>'; return html; } // 生成表格内容(可直接插入到邮件HTML中) const alertTableHtml = generateAlertTable(alerts);
这段代码会自动将同一应用下的不同告警类型分行展示,完全匹配你的需求。
优化数据结构建议
如果觉得嵌套字典的遍历不够直观,可将数据调整为扁平数组格式,更便于维护和遍历:
const optimizedAlerts = [ { category: "Services", appName: "App A", alertType: "Connection Error", message: "无法连接到数据库", timestamp: "2024-05-20 10:30" }, { category: "Services", appName: "App A", alertType: "Connection Error", message: "API响应超时", timestamp: "2024-05-20 10:45" }, // 其他告警项... ];
对应的表格生成代码会更简洁:
function generateOptimizedAlertTable(alerts) { let html = '<table border="1" cellpadding="8" cellspacing="0">'; html += '<thead><tr><th>告警分类</th><th>应用名称</th><th>告警类型</th><th>告警消息</th><th>时间戳</th></tr></thead><tbody>'; alerts.forEach(item => { html += `<tr> <td>${item.category}</td> <td>${item.appName}</td> <td>${item.alertType}</td> <td>${item.message}</td> <td>${item.timestamp}</td> </tr>`; }); html += '</tbody></table>'; return html; }
邮件适配注意事项
HTML邮件对CSS支持有限,建议使用内联样式替代外部样式表,确保在不同邮箱客户端显示正常:
<table style="border-collapse: collapse; width: 100%;"> <thead> <tr style="background-color: #f0f0f0;"> <th style="border: 1px solid #ccc; padding: 8px;">告警分类</th> <th style="border: 1px solid #ccc; padding: 8px;">应用名称</th> <!-- 其余表头项 --> </tr> </thead> <!-- 表格内容 --> </table>
内容的提问来源于stack exchange,提问作者texas697
相关产品推荐
相关产品推荐

