[英]Iterating through array in SendGrid email template
我正在嘗試使用 Ruby on Rails 遍歷集合並在 SendGrid 模板中顯示信息。
recipient = SendGrid::Recipient.new("sergio@gmail.com")
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 現在使用 handlebars 提供來自交易電子郵件的迭代器,這里是文檔以獲取更多信息:
https://sendgrid.com/docs/for-developers/sending-email/using-handlebars/#basic-iterator
迭代數據示例:
{
"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 發送郵件。
不幸的是,此時 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
"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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.