You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SendGrid代码编辑器中用Handlebars渲染JSON动态邮件模板全量数据

在SendGrid事务模板中渲染深层JSON数据为文本的解决方案

1. 渲染数组/深层对象为JSON文本

SendGrid的Handlebars默认没有内置JSON序列化函数,但可以通过两种方式实现需求:

方法一:自定义助手(生产环境推荐)

调用SendGrid API发送邮件时,可在请求中注册自定义Handlebars助手,实现JSON序列化和类型检测:

{
  "personalizations": [
    {
      "to": [{"email": "user@example.com"}],
      "dynamic_template_data": {/* 你的测试数据 */},
      "helpers": {
        "json": function(ctx) { return JSON.stringify(ctx); },
        "isArray": function(ctx) { return Array.isArray(ctx); },
        "isObject": function(ctx) { return typeof ctx === 'object' && !Array.isArray(ctx) && ctx !== null; }
      }
    }
  ],
  "template_id": "你的模板ID"
}

模板中即可这样使用:

<table>
  {{#each this}}
    <tr>
      <td>{{@key}}</td>
      <td>
        {{#if (isArray this)}}
          {{json this}}
        {{else if (isObject this)}}
          {{json this}}
        {{else}}
          {{this}}
        {{/if}}
      </td>
    </tr>
  {{/each}}
</table>

方法二:纯模板递归实现(编辑器内测试适用)

如果仅在模板编辑器中测试,不想修改API请求,可利用SendGrid内置的typeOf助手,写递归内联模板模拟JSON序列化:

{{#*inline "renderJSON"}}
  {{#if (eq (typeOf this) "array")}}
    [{{#each this}}{{> renderJSON this}}{{#unless @last}}, {{/unless}}{{/each}}]
  {{else if (and (eq (typeOf this) "object") (ne this null))}}
    {{{#each this}}"{{@key}}": {{> renderJSON this}}{{#unless @last}}, {{/unless}}{{/each}}}
  {{else if (eq (typeOf this) "string")}}
    "{{this}}"
  {{else}}
    {{this}}
  {{/if}}
{{/inline}}

<table>
  {{#each this}}
    <tr>
      <td>{{@key}}</td>
      <td>{{> renderJSON this}}</td>
    </tr>
  {{/each}}
</table>

该片段会递归将数组、对象渲染为JSON格式文本,字符串自动添加引号,基本类型直接输出。

2. 检测数组/对象类型

SendGrid Handlebars没有直接提供isArray或isObject方法,但可通过内置typeOf助手结合eq判断:

  • 判断数组:{{#if (eq (typeOf this) "array")}}...{{/if}}
  • 判断对象(排除null):{{#if (and (eq (typeOf this) "object") (ne this null))}}...{{/if}}

3. 调试输出

SendGrid模板编辑器没有专门的log方法,但上述JSON渲染方式可直接将数据以文本形式输出在邮件中,完全满足测试调试需求。

内容的提问来源于stack exchange,提问作者Jim Craane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 07:25:20