Dave Sag
Dave Sag

Reputation: 13486

Mandrill — How to format complex data for handlebars templates

I am trying to send a templated email via Mandrill but am having issues with the templates picking up the data I am sending.

The docs say that I need to convert my data to arrays of [{ name: 'propertyName', content: 'the content' }]

The example they give is as follows

Data

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

Template

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

Result

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

In my case the data is more complex.

I have something like

{
  "firstname": "Tyler",
  "lastname": "Durden",
  "fullname": "Tyler Durden",
  "email": "[email protected]",
  "company": {
    "name": "Company 1",
    "role": {
      "slug": "supplier",
      "name": "Supplier"
    }
  }
}

which I convert to name:content pairs as follows, to send as the global_merge_vars

[
   { name: 'firstname', content: 'Tyler' },
  { name: 'lastname', content: 'Durden' },
  { name: 'fullname', content: 'Tyler Durden' },
  { name: 'email', content: '[email protected]' },
  {
    name: 'company',
    content: [
      { name: 'name', content: 'Company 1' },
      {
        name: 'role',
        content: [
          { name: 'slug', content: 'supplier' },
          { name: 'name', content: 'Supplier' }
        ]
      }
    ]
  }
]

And my template is

Subject

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

Body

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

But the result is

Subject

Dear has been approved.

Body

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

I have set up Mandrill to use handlebars as its template language.

What am I missing?

Upvotes: 2

Views: 544

Answers (1)

Dave Sag
Dave Sag

Reputation: 13486

After some trial and error I have worked this out. It turns out only the top level object needs to be turned into a name, content pair. The lower order object structure can stay as a normal JSON object.

So

{
  "name": "user"
  "content": {
    "firstname": "Tyler",
    "lastname": "Durden",
    "fullname": "Tyler Durden",
    "email": "[email protected]",
    "company": {
      "name": "Company 1",
      "role": {
        "slug": "supplier",
        "name": "Supplier"
      }
    }
  }
}

with template subject: Hello {{user.firstname}}

and body

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

Works fine.

The docs were a bit misleading in this regard.

Upvotes: 3

Related Questions