Reputation: 111
If I had the string:
const html =
`<div>
<button>Increase Count</button>
<div>{{ 'Double count:' + count * 2 }}</div>
<div>{{ age }}</div>
</div>`
With handlebarJs I can evaluate the string with
const template = Handlebars.compile(html);
template({ count:4, age:10, name:'John' });
Which would return
`<div>
<button>Increase Count</button>
<div>Double count: 8</div>
<div>10}</div>
</div>`
Is there a way (within or without) using handlebarJs to return all the variables used to evaluate the string.
In this case we should get: [count, age]
and not name
because is is not used.
I was thinking of using regex, but it would be hard to isolate just the variables within the js.
const regex = /{{([^}]*)}}/g;
const htmlString = '<html><body>Hello, {{name}}!</body></html>';
let variables = [];
let match;
while (match = regex.exec(htmlString)) {
variables.push(match[1]);
}
console.log(variables); // Output: ["name"]
Upvotes: 0
Views: 254
Reputation: 111
To solve this, I got all the text inside the double curly brackets, then used acorn and acorn-walk to parse the JS and find identifiers.
Upvotes: 2