我正在尝试使用 Ruby on Rails 迭代集合并在 SendGrid 模板中显示信息。
recipient = SendGrid::Recipient.new("[email protected]")
recipient.add_substitution("username", user.github_id)
recipient.add_substitution("numbers", [1,2,3,4])
在 Gmail 中,此模板的形式为:
sergiotapia
ARRAY(0x85b9d90)
模板的实际代码,从 SendGrid 的编辑器复制:
<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>
如何迭代 SendGrid 模板中的通用数组或对象?对于这个特定的示例,用户有很多
posts
,我只想在 <li>
元素中显示用户帖子的标题。
我只是用一个简单的数字数组尝试一下,看看 SendGrid 是如何工作的。
2018 年 8 月更新:
Sendgrid 现在使用手柄提供交易电子邮件中的迭代器,请参阅文档以获取更多信息:
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>
数据迭代示例:
{
"people":[{"name":"Bob"},{"name":"Sally"}]
}
代码:
{{#if people}}
<p>People:</p>
{{#each people}}
<p>{{this.name}}</p>
{{/each}}
{{/if}}
结果:
人:
鲍勃
莎莉
{{#each data.products}}
{{name}}: {{price}} <br/>
{{/each}}
{"data":{"products": [{"name": "Tomato", "price": "5"}, {"name": "Banana", "price": "8"}]}}
更新
SendGrid 现在支持动态模板!
您可以在他们的博客上阅读: https://sendgrid.com/blog/how-to-use-sendgrids-dynamic-templates-for-your-transactional-emails/
旧答案:
搜索此结果导致以下GitHub问题。所以 SendGrid 还不可能(还?)。
但是还有其他方法可以做到这一点。使用 sendwithus 您可以访问更强大的模板编辑器,支持循环和迭代。
只需使用您自己的 SendGrid API 密钥进行设置,您就可以使用 sendwithus 模板中的数组,该模板将使用 SendGrid 发送邮件。
"businessContributors" : [
{
"total" : {
"amount" : 11340,
"title" : "Dhama Ji Total"
},
"list" : {
"Dhama Ji Paid" : -296310,
"HDFC Account" : 0,
"Dhama Ji Received" : 307650
},
"title" : "Dhama Ji Owner Account"
},
{
"total" : {
"amount" : -1270,
"title" : "Rahul Total"
},
"list" : {
"Rahul Paid" : 243838,
"Rahul Received" : 242568
},
"title" : "Rahul Account"
},
]
in email template :-
<h4>Business Contributors </h4>
<ul>
{{#each businessContributors}}
<li> {{this.title}} <br>
{{#each this.list}}
{{@key}} = {{this}} <br>
{{/each}} </li>
<hr style="height: 2px; background-color: black;"><br>
<h2>{{this.total.title}}</h2><br>
<h2>{{this.total.amount}}</h2>
<br><br>
{{/each}}
</ul>
不幸的是,SendGrid 目前提供的模板非常少。模板不支持数组作为值,并且没有条件或循环控件,因此您需要在构建模板和模板内容之前预先确定所有内容。更强大的模板系统即将推出。
这是一个解决方法 Sendgrid 尚未为此更新其模板引擎
大家好,我需要在我的 sendgrid 邮件中进行一些迭代,现在遇到了这个问题,我有一个暂时的解决方法来解决这个问题。这是我解决这个问题的方法
然后通过sendgrid将整个字符串内容作为消息发送
public void sendSimpleMessage(String message,
String subject,
String toEmail,
String fromEmail){
Email from = new Email(fromEmail);
Email to = new Email(toEmail);
Content content = new Content("text/html", message);
Mail mail = new Mail(from, subject, to, content);
SendGrid sg = new SendGrid(sendgridApiKey);
Request request = new Request();
try {
request.method = Method.POST;
request.endpoint = "mail/send";
request.body = mail.build();
sg.api(request);
} catch (IOException ex) {
ex.printStackTrace();
}
}
希望对某人有帮助 https://github.com/sendgrid/sendgrid-nodejs/issues/221#issuecomment-361489007