Template literals, when used with tags, seem to get compiled down to an array containing the strings and the substitutions.
For example:
mytag `my name is ${'Anthony'}`
seems to get compiled down to something representing:
mytag.apply(null, [['my name is '], 'Anthony'])
My question is, how could I take `my name is ${'Anthony'}` and get the [['my name is '], 'Anthony'] "decompiled" representation?
I've included a snippet to demonstrate the above is true.
function mytag(a, ...b) {
for (let i = 0; i < a.length; i++) {
console.log(a[i]);
console.log(b[i]);
}
}
mytag`hello ${'world'}, how are ${'you'}`;
mytag.apply(null, [['hello', ', how are ', ''], 'world', 'you']);
Edit
Just to clarify my overall goal.
I'd like to have the ability to pass a template literal into a tag.
Here is a slightly more complicated example,
const myliteral = `my name is ${() => 'Anthony'}`;
// would "decompile" to [['my name is'], f]
mytag.apply(null, fnToGetDecompiledRep(myliteral));
I'm using a function in myliteral to demonstrate that the function does not get evaluated. You can assume mytag has logic to evaluate functions.
You could just make
function templateValues(...args) {
return args;
}
and call it as
console.log(templateValues `my name is ${'Anthony'}`)
console.log(templateValues `hello ${'world'}, how are ${'you'}`;
I'd like to get the array representation without the use of a tag
const myliteral = `my name is ${() => 'Anthony'}`; // would "decompile" to [['my name is'], f] mytag.apply(null, fnToGetDecompiledRep(myliteral));
No, that cannot work. myLiteral would be assigned string value that the literal expression creates here. You cannot "decompile" it afterwards. You need to use
const myParts = templateValues `my name is ${() => 'Anthony'}`;
// same as … = [['my name is'], () => 'Anthony'];
myTag.apply(null, myParts); // or myTag(...myParts)
There is no way around a tag to get the template values instead of a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With