问题
I'm sending a single transactional email to a single user and want to embed a list of items in the email. I can add single substitution values using the NPM package "sendgrid" in Node.js - https://github.com/sendgrid/sendgrid-nodejs:
email.addFilter('templates', 'enable', 1);
email.addFilter('templates', 'template_id', '11122233445....');
email.addSubstitution('{{TOKEN1}}', 'My Token1 Replacement');
But I can't see how add a list of items to the template in sendgrid. Using Mandrill I can use Handlebars and do the following. The list:
items: [
{name: "one", url: "/one"},
{name: "two", url: "/two"},
];
In the template:
<ul>
{{#each ITEMS}}
<li>
{{name}} - <a href="{{url}}">Blah</a>
</li>
{{/each}}
</ul>
Then in the code:
var rcpt = { "rcpt": email,
"vars": [
{ "name":"ITEMS", "content": items }
]
};
mergeVars.push(rcpt);
var message = { ...
"merge_vars": mergeVars,
}
mandrillClient.messages.sendTemplate({... "message": message });
Resulting in:
<ul>
<li>one <a href="/one">Blah</a></li>
<li>two <a href="/two">Blah</a></li>
</ul>
Is there a way to do this in Sendgrid?
回答1:
SendGrid doesn't have each
logic in Templates.
The best workaround for this is to have in the Template:
<ul>
{item1}
{item2}
{item3}
</ul>
Then in your substitutions, you'd populate either the appropriate <li> item 1 details</li>
or NULL as the case may be. Make sure that your template has as many Substitution tags as your max list size, and that you have default values for those items of NULL, so that they're populated even if there's not an item.
来源:https://stackoverflow.com/questions/33903789/list-of-substitution-tokens-in-sendgrid