如何在SendGrid模板中序列化未知结构的JSON对象?
在SendGrid模板中序列化未知结构的对象
可以实现,SendGrid的模板基于Handlebars语法,默认直接输出对象会显示[object Object],你需要自定义一个Handlebars助手函数来实现JSON序列化,具体步骤如下:
步骤1:在发送邮件的代码中注册自定义助手
以Node.js环境为例,使用SendGrid SDK时,你可以在配置邮件模板时添加一个json助手,实现JSON.stringify的功能:const sgMail = require('@sendgrid/mail'); sgMail.setApiKey(process.env.SENDGRID_API_KEY); // 注册自定义Handlebars助手 sgMail.setSubstitutionWrappers('{{', '}}'); sgMail.addHelper('json', function(context) { return JSON.stringify(context); }); // 构造邮件数据 const msg = { to: 'recipient@example.com', from: 'sender@example.com', templateId: 'your-template-id', dynamicTemplateData: { test: {"foo": { "bar": {"foo2": "bar2"}}} } }; sgMail.send(msg);步骤2:在SendGrid模板中使用该助手
修改你的模板代码,调用自定义的json助手来序列化对象:... what is inside the test object: {{json test}}如果需要避免HTML转义(比如保留JSON的引号和大括号格式),可以使用三个大括号:
... what is inside the test object: {{{json test}}}
这样就能得到你期望的JSON字符串输出了。
内容的提问来源于stack exchange,提问作者LakiGeri
相关产品推荐
相关产品推荐

