3

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.

4
  • Maybe this helps stackoverflow.com/questions/22607806/…
    – luislhl
    Commented Nov 11, 2016 at 2:23
  • No. To defer evaluation of expressions in template string, you'd need something alike what was done in C# to support LINQ - ability to get access to parse tree of any expression at run time, and ability to evaluate that expression in some context. No such thing exists in javascript - um, well, there is eval but I don't think it's a good idea to use it for this.
    – artem
    Commented Nov 11, 2016 at 2:23
  • I figured that might be the case, just wanted to check in case I'm missing something. Thanks.
    – Paul
    Commented Nov 11, 2016 at 3:05
  • Possible duplicate of Can you "dumb down" ES6 template strings to normal strings?
    – user663031
    Commented Nov 11, 2016 at 3:51

1 Answer 1

4

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.

1
  • 1
    I figured the same last night, but credit to you for posting. Thanks.
    – Paul
    Commented Nov 11, 2016 at 18:44

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.