Open liudonghua123 opened 2 years ago
For my question, I wrote a simple function to achieve it finally.
// Typescript version
function template(expr: string, locals: { [key: string]: string }): string {
const localsKeys = Object.keys(locals);
const localsValues = localsKeys.map(i => locals[i]);
try {
const compile = (expr: string, args: string | string[]) => Function(...args, 'return `' + expr + '`;');
const result = compile(expr, localsKeys)(...localsValues);
return result;
} catch (err: any) {
console.error(err);
return err.message;
}
}
// Plain js version
function template(expr, locals) {
const localsKeys = Object.keys(locals);
const localsValues = localsKeys.map(i => locals[i]);
try {
const compile = (expr, args) => Function(...args, 'return `' + expr + '`;');
const result = compile(expr, localsKeys)(...localsValues);
return result;
} catch (err) {
console.error(err);
return err
}
}
Then I can invoke template
function like this.
const obj = {
a: 123,
b: "hello",
c: true
}
const exp = "${a.toString(2)}-${b.toLowerCase()}-${c}"
const result = template(exp, obj);
console.info(`${exp} = ${result}`);
Hi, I have the following code and I want to make this work like template literals. But it does not support invoke methods of variables in template string.