Back to Sendgrid Nodejs

Transactional Templates

docs/use-cases/transactional-templates.md

8.1.62.1 KB
Original Source

Transactional Templates

For this example, we assume you have created a dynamic transactional template in the UI or via the API. Following is the template content we used for testing.

Email Subject:

text
{{ subject }}

Template Body:

html
<html>
<head>
    <title></title>
</head>
<body>
Hello {{ name }},



I'm glad you are trying out the template feature!



I hope you are having a great day in {{ city }} :)



</body>
</html>
js
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
  to: '[email protected]',
  from: '[email protected]',
  templateId: 'd-f43daeeaef504760851f727007e0b5d0',
  dynamicTemplateData: {
    subject: 'Testing Templates',
    name: 'Some One',
    city: 'Denver',
  },
};
sgMail.send(msg);

There's no need to specify the substitution wrappers as it will assume that you're using Handlebars templating by default.

Prevent Escaping Characters

Per Handlebars' documentation: If you don't want Handlebars to escape a value, use the "triple-stash", {{{

If you include the characters ', " or & in a subject line replacement be sure to use three brackets.

Email Subject:

text
{{{ subject }}}

Template Body:

html
<html>
<head>
    <title></title>
</head>
<body>
Hello {{{ name }}},



I'm glad you are trying out the template feature!



<%body%>



I hope you are having a great day in {{{ city }}} :)



</body>
</html>
js
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
  to: '[email protected]',
  from: '[email protected]',
  subject: 'Hello world',
  text: 'Hello plain world!',
  html: '<p>Hello HTML world!</p>',
  templateId: 'd-f43daeeaef504760851f727007e0b5d0',
  dynamic_template_data: {
    subject: 'Testing Templates & Stuff',
    name: 'Some "Testing" One',
    city: '<b>Denver<b>',
  },
};
sgMail.send(msg);