I'm trying to iterate through a collection and display information in a SendGrid template using Ruby on Rails.
recipient = SendGrid::Recipient.new("[email protected]")
recipient.add_substitution("username", user.github_id)
recipient.add_substitution("numbers", [1,2,3,4])
In gmail, this template arrives as:
sergiotapia
ARRAY(0x85b9d90)
The actual code for the template, copied from SendGrid's editor:
<html>
<head>
<title></title>
</head>
<body>
<div><%body%></div>
<div>username</div>
<div>numbers</div>
<p>This is a small example email.</p>
</body>
</html>
How can I iterate through a generic array or object in a SendGrid template? For this particular example, a user has many posts
and I just want to show the title of the user's posts in a <li>
element.
I'm just trying things out with a simple number array to see how it SendGrid works.
Update August 2018:
Sendgrid now offers iterators from the transactional email using handlebars, here's to the docs for more info:
https://docs.sendgrid.com/for-developers/sending-email/using-handlebars#iterations
Template
<ol>
{{#each user.orderHistory}}
<li>You ordered: {{this.item}} on: {{this.date}}</li>
{{/each}}
</ol>
Test data
{
"user": {
"orderHistory": [
{ "date": "2/1/2018", "item": "shoes" },
{ "date": "1/4/2017", "item": "hat" }
]
}
}
Resulting HTML
<ol>
<li>You ordered: shoes on: 2/1/2018</li>
<li>You ordered: hat on: 1/42017</li>
</ol>