by somat · 1y ago · 0 comments
Do they really not support the equivalent to
let template = 'hello ${name}';
let n1 = template.format({ 'name':'joe' });
let n2 = template.format({ 'name':'bob' });
I am not really a javascript programmer. but I was writing some and wanted to store a bunch of templates then fill them out dynamically and was unable to figure out how to do it with the native javascript template system. So I ended up having to write my own. As it appears to be a huge obvious hole in missing functionality, I have to ask. Am I holding it wrong?While writing this up I was rereading the mdn page on template literals, perhaps tagged templates would do what I wanted, I don't remember why I did not use them(I think it is still not possible to store the template), but on first glance, yeah, lamentations about the unintuitive syntax and weird features.
const tpl = ({ name }) =>
`hello ${name}`;
const n1 = tpl({ name: "joe" });
const n2 = tpl({ name: "bob" });
Or if you don’t like the duplication of property names, you could do it without destructuring: const tpl = (o) =>
`hello ${o.name}`;
Look for the free online book ”You don’t know JS”, it is good reading. const template = ({name}) => `hello ${name}`;
const n1 = template({ name: 'joe' });
(Tagged templates won’t help here because the bit in curly braces is an expression which is evaluated to a value first; you’d need some kind of macro system to get access to the original variable name at runtime.)