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?