MsSql - 2014
I recently started programming on nodeJs.
I have email template in data base tabel.
For eg:
message1 : Hello {friendName},
Happy Birthday {friendName}.
Thank you,
{Name}
message2 : Hello All,
The total expense as;
{ListOfExpense}
Thank you,
{Name}
For message 1 -- I have UI input as name and friendName on input obj. For message 2 -- I have UI input of List of expense on input.expense obj.
I am able to read from DB let say in var dbMessage = message 1 or message 2;
I want to use template engines to change {} values according to template and store on the text so I can set on the body.
I am using nodemailer to send mail;
var mailOptions={
to : req.query.to,
subject : req.query.subject,
text : ? // I want use text as email body.
}
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
res.end("error");
}else{
res.end("sent");
}
});
Kindly help.
Well, you can do this a bunch of ways.
You're only doing string interpolation so you can very easily use a function with ES6 template literals..
function myTemplate(env) {
const template = `Hello ${env.friendName},
Happy Birthday ${env.friendName}.
Thank you,
${env.Name}`;
return template.replace(/\n/, '<br>');
}
var mailOptions={
to : req.query.to,
subject : req.query.subject,
text : myTemplate({friendName: "foo", Name: "Bar"});
};
You may want to trim it up a bit, but that'll get you started.
Other template languages include Pugjs (previously Jade), Handlebars.js, and _.template. Typically these more professional third party templates compile down to a JavaScript function, and they're called the same way as our function above. All of the above engines have to be set up in their own fashion...
const pug = require('pug');
const myTemplate = pug.compileFile('myPugPath.pug');
myTemplate({friendName: "foo", Name: "Bar"});
Also, that you're sending email has nothing to do with this question. Just write an HTML string somehow (ex., using ES6 Template literals, or pug) and then send the email with the mime type properly set (text/html
), and the body set to the html.
If you have the template in your database then rather than using pug.compileFile
you would simply use pug.compile(resultFromDb.pugTemplate)
. Check the documentation on pug for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With