Mandrill - 如何格式化把手模板的复杂数据

时间:2018-05-05 10:24:24

标签: templates mandrill

我正在尝试通过Mandrill发送模板化的电子邮件,但是我收到的数据存在问题,我正在发送数据。

The docs说我需要将我的数据转换为[{ name: 'propertyName', content: 'the content' }]

的数组

他们给出的例子如下

数据

"global_merge_vars": [
  {
    "name": "user_name",
    "content": "Mandrill_User1"
  }
]

模板

<p>Thanks for registering! Your username is {{user_name}}.</p>

结果

<p>Thanks for registering! Your username is Mandrill_User1.</p>

在我的情况下,数据更复杂。

我有类似

的东西
{
  "firstname": "Tyler",
  "lastname": "Durden",
  "fullname": "Tyler Durden",
  "email": "tyler.durden@testy.tes",
  "company": {
    "name": "Company 1",
    "role": {
      "slug": "supplier",
      "name": "Supplier"
    }
  }
}

我转换为namecontent对,如下所示,发送为global_merge_vars

[
   { name: 'firstname', content: 'Tyler' },
  { name: 'lastname', content: 'Durden' },
  { name: 'fullname', content: 'Tyler Durden' },
  { name: 'email', content: 'tyler.durden@testy.tes' },
  {
    name: 'company',
    content: [
      { name: 'name', content: 'Company 1' },
      {
        name: 'role',
        content: [
          { name: 'slug', content: 'supplier' },
          { name: 'name', content: 'Supplier' }
        ]
      }
    ]
  }
]

我的模板是

主题

Dear {{user.firstname}} {{company.name}} has been approved.

<html>
  <body>
    <p>Dear {{user.firstname}},</p>
    <p>Your company {{company.name}} has been approved.</p>
  </body>
</html>

但结果是

主题

亲爱的已被批准。

<html>
  <body>
    <p>Dear ,</p>
    <p>Your company  has been approved.</p>
  </body>
</html>

我已将Mandrill设置为使用handlebars作为模板语言。

我错过了什么?

1 个答案:

答案 0 :(得分:1)

经过一些试验和错误,我已经解决了这个问题。事实证明,只有顶级对象需要转换为namecontent对。低阶对象结构可以作为普通的JSON对象保留。

所以

{
  "name": "user"
  "content": {
    "firstname": "Tyler",
    "lastname": "Durden",
    "fullname": "Tyler Durden",
    "email": "tyler.durden@testy.tes",
    "company": {
      "name": "Company 1",
      "role": {
        "slug": "supplier",
        "name": "Supplier"
      }
    }
  }
}

包含模板主题:Hello {{user.firstname}}

和身体

<html>
  <body>
    <p>Dear {{user.firstname}},</p>
    <p>Your company {{user.company.name}} has been approved.</p>
  </body>
</html>

工作正常。

在这方面,文档有点误导。