janl / mustache.js

Minimal templating with {{mustaches}} in JavaScript

Home Page:https://mustache.github.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to invoke methods of variables in template string.

liudonghua123 opened this issue · comments

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()

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