How to invoke methods of variables in template string.
liudonghua123 opened this issue · comments
liudonghua commented
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.
const mustache = require('mustache');
function test() {
const obj = {
a: 123,
b: "HELLO",
c: true
}
// this does not work as expected, rendered as "--true" not "1111011-hello-true"
// const exp = "${a.toString(2)}-${b.toLowerCase()}-${c}"
const exp = "${a}-${b}-${c}" // this works, rendered as "123-hello-true"
mustache.tags = ['${', '}'];
const result = mustache.render(exp, obj, );
console.info(`${exp} = ${result}`)
}
test()
liudonghua commented
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}`);