Simple template engine in JavaScript
24 October, 2020
Recently I had a task, that included creating simple templates. Nothing special, just using JavaScript replace placeholders with provided values. Obviously it's better to have some general solution in place, so next time any change wouldn't be painful.
Examples of some strings with placeholders:
- "Hello, {name}!"
- "The answer is {value}"
- etc
There is no complicated logic inside of the template. Therefore, I need just an object with values to replace, and some mechanism to find correlation between placeholder name and keys in the values object.
So I came up with following solution:
export type TTemplateData = {
[key: string]: string;
};
export const templateEngine = (inputString: string, data: TTemplateData) => {
return inputString.replace(/{\s*(\w*)\s*}/g, (match, key) => {
return data.hasOwnProperty(key) ? data[key] : '';
});
};
You might also be interested in the following posts:
Let's talk about one of the most well-known features of the web - registration. Not particularly the whole process, but in particular one aspect, email. For almost anything on the web, we need an email: ordering goods, registering for a service, receiving notifications, etc. It's logical that if we need emails so much, then we'll need to somehow be sure that the user has provided a correct one.