Placeholders in string templates
June 23, 2022
Some time ago I was supposed to write a simple script that reads a mail template from a .html
file and sends it to the recipient.
The template included some dynamic content like a name or greeting, so we had to add something like placeholders to the template.
Since I didn’t want to use a template language like EJS or Pug because I thought it was overkill, I created my own function to render the variables, which is actually nothing special, but I wanted to share with you anyway.
This is what the mail template looks like. The placeholders are enclosed in ${}
and will be replaced later with the provided variables when reading the file.
<html>
<body>
<p>Hello ${firstname}, do you like ${food}?</p>
<p>Bye ${firstname}!</p>
</body>
</html>
The function renderTemplate()
receives a path to a mail template and an object where the keys have the names of the placeholders. The placeholders get replaced via JavaScripts string replace() function and a regular expression.
Simple as that.
const fs = require("fs")
/**
* Render the given template with the given parameters.
*
* @param {string} path Template path
* @param {Object} params Template parameters
* @returns {string}
*/
const renderTemplate = (path, params = {}) => {
let template = fs.readFileSync(path, {
encoding: "utf-8",
})
for (const key in params) {
const re = new RegExp(`\\$\{${key}\}`, "g")
template = template.replace(re, params[key])
}
return template
}
const template = renderTemplate("./template.html", {
firstname: "Peter",
food: "Pizza",
})
console.log(template)
The rendered output including the passed in variables:
<html>
<body>
<p>Hello Peter, do you like Pizza?</p>
<p>Bye Peter!</p>
</body>
</html>
This solution should work for any kind of strings where you want to insert some dynamic content and is not limited to mail templates or JavaScript of course. Very simple and straightforward but also quite useful in my opinion.
This is my personal blog where I mostly write about technical or computer science based topics. Check out my GitHub profile too.