asdjfiasd
asdjfiasd

Reputation: 1730

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?

Upvotes: 4

Views: 1931

Answers (2)

Ola
Ola

Reputation: 21

I'm sorry for answering this question an entire year after it was posted.

I ran into the same issue (albeit in another way), and created a function/package to solve it:

https://github.com/OlaHulleberg/varEx

I've intentionally made the syntax similar, but not identical to literal tags, anyways here's how to use it:

varEx("Any string you want plus a $[variable] block", objectToResolveFrom);

And here's an example:

// Include varEx
const { varEx } = require('varex');

// This is the object we use to resolve variables
const object = {
    var1: "Example",
    var2: "Yet another one",
    var3: "You can even include [] brackets here, even $[variable blocks] doesn't break this",
    varObj: {
        var1: "Supports nesting as well!",
        varArray: [
            "Need arrays? Have at it!"
        ]
    }
};

// Output the result
console.log(
    varEx("This is an $[var1], and here is $[var2]. $[var3]. $[varObj.var1] $[varObj.varArray[0]]", object)
);

Please feel free to contribute, and give me feedback if you have any! :)

Upvotes: 2

Quentin
Quentin

Reputation: 944206

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.

Upvotes: 4

Related Questions