Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to invoke methods of variables in template string. #804

Open
liudonghua123 opened this issue Aug 2, 2022 · 1 comment
Open

How to invoke methods of variables in template string. #804

liudonghua123 opened this issue Aug 2, 2022 · 1 comment

Comments

@liudonghua123
Copy link

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()
@liudonghua123
Copy link
Author

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}`);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants
@liudonghua123 and others