Can ES6 template literals be substituted at runtime (or reused)?

To make these literals work like other template engines there needs to be an intermediary form.

The best way to do this is to use the Function constructor.

const templateString = "Hello ${this.name}!";
const templateVars = {
    name: "world"    
}

const fillTemplate = function(templateString, templateVars){
    return new Function("return `"+templateString +"`;").call(templateVars);
}

console.log(fillTemplate(templateString, templateVars));

As with other template engines, you can get that string from other places like a file.

Some issues can appear using this method (for example, template tags would be harder to add). You also can’t have inline JavaScript logic, because of the late interpolation. This can also be remedied with some thought.

Leave a Comment