I am looking for a very simple way to do templating for text input. I need to handle simple functions like upper case, substring, trim etc. I'm just handling text. For example:
Hello {{profile.name}}, the following date {{formatDate(event.date, 'dd.mm.yyyy')}} is free.
I imagine calling it like this:
TemplateEngine.render(
'Hello {{profile.name}}, the following date {{formatDate(event.date, 'dd.mm.yyyy')}} is free.',
{
profile: { name: 'Tom' },
event: { date: 1682349765 }
},
{
formatDate: (input, format) => moment(input).format(format)
});
My current approach only works with non-nested data and no functions. It gets more and more complicated so my question now: Does anyone know how to accomplish something similar but with those features?
I already looked at handlebarsjs but it seems like overkill for what I want to do. Best case would be to have no external dependency at all.
export class TemplateEngine {
public static render(template, data, functions) {
return template.replace(/{{(.*?)}}/g, (match) => {
return data[match.split(/{{|}}/).filter(Boolean)[0].trim()];
});
}
}