Paul
Paul

Reputation: 36349

ES6 template strings as variable?

Seems like template strings would be a really useful thing to pass into a module, let's say you want to let the calling code provide how they want to format some output.

Thing is, at least in the node REPL, it appears that the template string is evaluated immediately, so you can't. For example:

var template = `Time: ${now} | Message: ${thing.msg}`;
var thing = {msg : 'Something wicked this way comes'};
var now = new Date();

Attempting to enter those three lines into the REPL will error out as thing has not yet been defined on the line of the template.

Is there a way around this? I'd really like to pass the template string itself around as a variable.

Note that I saw the question about "dumbing down" template strings before asking this. It's not the same question at all, as what I'm asking about is deferring execution, not converting to a normal string.

Upvotes: 3

Views: 2299

Answers (1)

Fernando
Fernando

Reputation: 280

The only thing I can think of is wrapping the template in a lambda to defer execution. Not sure if that's useful for your use case? I'm thinking of something like:

var template = (now, thing) => `Time: ${now} | Message: ${thing && thing.msg}`;
var thing = {msg : 'Something wicked this way comes'};
var now = new Date();

console.log(template(now, thing));

Using ${thing && thing.msg} instead of ${thing.msg} prevents the console error, but will return 'Message: undefined' if the object doesn't exist.

Upvotes: 4

Related Questions