javascripttemplate-literals

Is it possible to defer the substitution of expressions into a template literal?


Is it possible to use template literals somehow before the values a known. Every demo on JS template literals looks like this:

var name = "John";
var s = `Hello ${name}`;

But in real world, templates are defined before we know variable values. Somewhere is defined template (on page load):

var s = `Hello ${name}`;

And then, 5 minutes later, when user logs in I want to use this template but it was already substituted so how to actually do it? Similar issue would be how to use template multiple times.

I can imagine having it some wrapper function but I want to have templates in JSON where there cannot be functions. Is it even possible?


Solution

  • No.

    Template strings are for populating at the time the template string is declared.

    If you want to define it early and populate it later, define it inside a function. (An option you've rejected).

    You might consider another template engine such as Nunjucks or EJS … but they'll still effectively be wrapped in a function.