0

I am attempting to use a template literal from a configuration file – imported as a string through json – in a templating function.

Per Can ES6 template literals be substituted at runtime?, I can easily define the callable function if I know the template literal to use when I am writing my code:

let errTemplate = (min) => `Value must contain at least ${min} characters.`;
console.log(errTemplate(10)); // Value must contain at least 10 characters.

However, this requires the template to be hard coded into the source code, which is bad practice by definition. (And as there will be an indeterminate number of instances of my template, with different messeges, it is not a functional approach.)

If I understand the proto-explanation found elsewhere, this fails when attempting to use a string sourced from my json config because a template literal is code – effectively a parser function – rather than being an interpreted string per se.

let errMessage = json.errMessage; // "Value must contain at least ${min} characters."
let errTemplate = (min) => `${errMessage}`;
console.log(errTemplate(10)); // undefined

Is there any simple and clean way to instantiate a configuration-sourced template funtion short of the verbose regExp-based parser to split it into constituent parts and a string rebuilder function to pull it all back together?

Rick
  • 397
  • 3
  • 16
  • Simple? Surely you read [the top answer on the question you linked](https://stackoverflow.com/a/37217166/1048572)! Do you not consider it clean? – Bergi Oct 13 '22 at 22:37
  • Sounds like you're looking for a real template engine. A simple regex replace might work as well, it's not that verbose. – Bergi Oct 13 '22 at 22:38
  • @Bergi – A function to build a function to build a function… Honestly, no, I don't call that particularly clean. But, then, a real tempate engine is even more complex, so I suppose it's the lesser of two convolutions. – Rick Oct 14 '22 at 22:44

0 Answers0