Kermit
Kermit

Reputation: 3407

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

I wish to send an email using a SendGrid template. I use the standard v3 api and a simple axios call.

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.
  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.
  3. Send the email.
  4. I expect the email to treat my HTML rows/columns as HTML.

My code (does not work - HTML is treated as text):

  //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

Upvotes: 14

Views: 15515

Answers (1)

Kermit
Kermit

Reputation: 3407

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. 😊

In the SendGrid Template - this syntax will interpret the variable textRows as plain text

{{textRows}}

In the SendGrid Template - this ayntax will interpret the variable textRows as HTML

{{{textRows}}}

Thanks to Kyle Roberts for posting the solution on github! 🎉

/K

Upvotes: 53

Related Questions