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

SendGrid模板中嵌套Handlebars {{each}}循环遍历订单对象数组失败问题求助

问题排查与解决方案

我帮你排查了下你的SendGrid Handlebars模板无法正常渲染的问题,主要是几个拼写错误和上下文路径的问题,具体如下:

核心问题点

  • 拼写不一致:你的JSON数据里的变体数组和字段名都是varient(e结尾),但模板里多处写成了variant(a结尾),比如{{#each variant}}和{{variant.varient_name}},这会导致Handlebars找不到对应变量。
  • 嵌套循环路径错误:在外部{{#each payload.order.lines}}循环中,当前上下文是单条订单商品行(line对象),要遍历该商品下的变体,需要明确指向this.product.varient,而不是直接写{{#each variant}}——因为变体数组并不在当前上下文的直接层级。
  • 内部循环变量引用错误:进入内部变体循环后,当前上下文已经是单个varient对象,所以直接用字段名(比如{{varient_name}}、{{quantity}})即可,不需要再加varient.前缀。

修正后的模板代码

{{#each payload.order.lines}}
<table class="module" role="module" data-type="code" border="0" cellpadding="20" cellspacing="0" width="100%" style="table-layout: fixed;" data-muid="a16c3fb2-992a-4f39-8c80-c285b41a1eb1">
  <tbody>
    <tr>
      <td>
        <div style="font-family: inherit; font-size:25px; text-align: inherit;"><strong>{{this.product.product_name}}</strong>
        </div>
        <div style="font-family: inherit; font-size:15px; text-align: inherit">
        </div>
        {{#each this.product.varient}}
        <div style="font-family: inherit; font-size:25px; text-align: inherit;"><strong>{{varient_name}}</strong></div>
        <div style="font-family: inherit; font-size:25px; text-align: inherit;">
        </div>
        <div style="font-family: inherit; font-size:15px; text-align: inherit; padding: 2px;">Quantity: {{quantity}} </div>
        <div style="font-family: inherit; font-size:15px; text-align: inherit; padding: 2px;">Total_Gross_Amount: {{total_gross_amount}} </div>
        <div style="font-family: inherit; font-size:15px; text-align: inherit; padding: 2px;">Total_Tax_Amount: {{total_tax_amount}} </div>
        <div style="font-family: inherit; font-size:15px; text-align: inherit; padding: 2px;">Total_Net_Amount: {{total_net_amount}} </div>
        {{/each}}
      </td>
    </tr>
  </tbody>
</table>
{{/each}}

额外排查建议

如果以后遇到类似渲染问题,可以在模板中临时添加{{log this}}语句,用来输出当前上下文的结构,帮助你确认变量的正确路径。比如在外部循环里加{{log this}},就能看到当前line对象包含哪些属性,方便快速定位路径问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 22:32:27