0

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()];
    });
  }

}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
perotom
  • 851
  • 13
  • 33
  • 2
    Perhaps JavaScript's [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) would be worth a look if you haven't investigated them already..? – motto Apr 24 '23 at 15:33
  • 2
    Does this answer your question? [Format string template with variables in Javascript](https://stackoverflow.com/questions/42279852/format-string-template-with-variables-in-javascript) – Heretic Monkey Apr 24 '23 at 15:56
  • Sounds like an interesting idea but is it possible to dynamically set the template? I want the template to be a user input. – perotom Apr 24 '23 at 16:53

1 Answers1

0

I think this is more complex than I thought. Something like a Parsing expression grammar is needed. There are online generators for something like that: https://pegjs.org/

perotom
  • 851
  • 13
  • 33