简体   繁体   English

如何在 JavaScript 中将动态数据 (HTML) 插入 SendGrid 模板

[英]How to insert dynamic data (HTML) into SendGrid Templates in JavaScript

I wish to send an email using a SendGrid template.我希望使用SendGrid模板发送电子邮件。 I use the standard v3 api and a simple axios call.我使用标准的 v3 api 和一个简单的 axios 调用。

I wish to send an email using a Template.我希望使用模板发送电子邮件。 The mail should contain a number of rows and columns.邮件应包含许多行和列。 I do not know how many rows/column there will be when creating the Template.我不知道创建模板时会有多少行/列。 The number of rows/columns will depend on data only known when composing the email.行数/列数将取决于仅在撰写电子邮件时已知的数据。

In my code I wish to:在我的代码中,我希望:

  1. Collect data and compose as many rows/columns as I wish using HTML or other recommended method.使用 HTML 或其他推荐的方法收集数据并根据需要组合尽可能多的行/列。
  2. Compose the message using Template and insert my HTML from (1) into the Template using "personalisations/dynamic_template_data" or any other recommended method.使用模板编写消息,并使用“personalisations/dynamic_template_data”或任何其他推荐的方法将 (1) 中的 HTML 插入到模板中。
  3. Send the email.发送电子邮件。
  4. I expect the email to treat my HTML rows/columns as HTML.我希望电子邮件将我的 HTML 行/列视为 HTML。

My code (does not work - HTML is treated as text):我的代码(不起作用 - HTML 被视为文本):

  //Coompose HTML
  let alertHtml = ''
  noteObjArray.forEach((nototObj)=>{
    ...
    alertHtml += (myDate !== '') ? `- ${someText} ${myDate } ` : ''
    ...
    alertHtml += '<br/>'
  })

  //Send mail using SendGrid  
  const mailSender = firebaseFunctionsConfig.sendgrid.sender
  const msg = {
    personalizations: [{
      to: [{email, name}],
      dynamic_template_data: {userName:name, amount, alertHtml}
    }],
    from: {email: mailSender.email, name: mailSender.name},
    reply_to: {email: mailSender.replyemail, name: mailSender.replyname},
    template_id: 'a-000078d4b2eb666940bbg1ee66s'
    // "content": [{"type": "text/html"}] 
  }

Thanks in advance!提前致谢! /K /K

To be able to insert HTML into a SendGrid template you simply have to insert the variable using three curly braces in the template instead of the standard two .为了能够将 HTML 插入到SendGrid模板中,您只需在模板中使用三个花括号而不是标准的两个花括号插入变量。 😊 😊

In the SendGrid Template - this syntax will interpret the variable textRows as plain text在 SendGrid 模板中 - 此语法将变量textRows解释为纯文本

{{textRows}}

In the SendGrid Template - this ayntax will interpret the variable textRows as HTML在 SendGrid 模板中 - 此 ayntax 将变量textRows解释为 HTML

{{{textRows}}}

Thanks to Kyle Roberts for posting the solution on github !感谢 Kyle Roberts 在github上发布解决方案! 🎉 🎉

/K /K

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM