TypeScript结合SendGrid时Handlebars迭代失效问题排查
问题:SendGrid邮件模板中Handlebars遍历数组失效
背景信息
表单提交的数据:
{ "sender": "tom_jones@test_email.com", "portfolios": [ { "id": "454453bb-8bc8-4eb1-9796-2e82046b3a12", "label": "Portafoglio_1" }, { "id": "882aa086-5c3b-45e0-a76c-7f5efae6ae12", "label": "Portafoglio_2" } ] }
TypeScript中SendGrid导入方式:
import sgMail from '@sendgrid/mail'
HTML模板中,sender字段可正常渲染:
<strong>${request.body?.sender}</strong>
但遍历portfolios数组的Handlebars代码无效果:
{{#each request.body?.portfolios}} <tr> <td style="padding: 0 15px 0 0;">{{this.label}} ({{this.id}})</td> </tr> {{/each}}
解决方案
1. 移除Handlebars中的ES6可选链语法?.
Handlebars原生不支持?.这种可选链操作符,模板里的request.body?.portfolios会被解析成无效路径,无法正确定位到数组。直接使用数组的顶级字段名(前提是数据传递正确)。
修改后的Handlebars代码:
{{#each portfolios}} <tr> <td style="padding: 0 15px 0 0;">{{this.label}} ({{this.id}})</td> </tr> {{/each}}
2. 确保动态模板数据传递正确
SendGrid的dynamicTemplateData是直接挂载到模板上下文的顶级对象,不需要嵌套在request.body下。发送邮件时,要把portfolios数组作为独立字段传递:
sgMail.send({ to: '目标邮箱@example.com', from: '发件邮箱@example.com', templateId: '你的SendGrid模板ID', dynamicTemplateData: { sender: request.body.sender, portfolios: request.body.portfolios // 直接传递数组到顶级上下文 } });
3. 验证数据源有效性
在发送前确认request.body.portfolios是有效的非空数组,避免因数据未正确解析导致遍历无效果:
// 检查数组是否存在且有内容 if (!request.body.portfolios || !Array.isArray(request.body.portfolios) || request.body.portfolios.length === 0) { console.warn('Portfolios数据无效'); // 可添加兜底逻辑 }
内容的提问来源于stack exchange,提问作者RobyB
相关产品推荐
相关产品推荐

