'Replacing placeholders in Email Template
What is the better way to replace placeholders in email module?
So, I have made a mail service which takes parameters like templatename , receiverMail & locals. locals have the values for placeholders.
var locals = {
username: "John",
website: "w3schools.com",
url: "http:// abc. com"
};
mail.sendMail('Registration', 'xyz.com', locals);
Relevant Code from Mail service :-
var mailOptions = {
from: "Abc <[email protected]>", // sender address
to: email, // list of receivers
subject: template_subject, // Subject line
html: template_html // html body
template_html contents the html body including the placeholders this is pulled from mongodb.
The locals are dynamic & can be increased or decreased.
What is the way to replace the placeholders?
Template:- (pls note these placeholders are dynamic & can be changed by admin)
<p>
Hi {{username}},
</p>
<p>
Xyz would like you to join it's network on <a href="{{url}}">xyz</a>.
<br />
Our website {{ website }}
</p>
Solution 1:[1]
We can use regular expressions to search and replace the template with the user specified data.
I have put up a small demo at
Here I am replacing the template with the actual data.
I am using the below code for replacing the data in the template:
for (var i = 0; i < data.length; i++) {
var obj = data[i];
output +="<p>" + template.replace(/\<%=(.*?)\%>/g, function(match, property) {
return obj[property];
}) + "</p>";
}
Solution 2:[2]
In this function replace all the tags with the values from the object passed in the parameter using RegExp
In this example use {{key}} in my html template
function replaceTemplateValues(template, values){
let html = template;
for (let key in values) {
html = html.replace(new RegExp('{{' + key + '}}', 'g'), values[key]);
}
return html;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anup |
| Solution 2 |
