Home > Article > Web Front-end > Can Template Literals Be Truly Reused?
Template literals in ES6 are often touted as powerful text manipulation tools, but a nagging question persists: can they truly be reused?
Unfulfillable Expectations
At first glance, template literals seem to promise dynamic substitutions only at declaration time. This begs the question: what is a template that remains static?
Breaking the Cycle
Contrary to popular belief, template literals can be reinvigorated with runtime substitutions using the Function constructor as an intermediary:
const template = "Hello ${this.name}!"; const variables = { name: "world" }; function fillTemplate(str, data) { return new Function("return `" + str + "`;").call(data); } console.log(fillTemplate(template, variables)); // Output: Hello world!
Anatomy of a Reusable Template
This technique allows for the following:
Addressing Caveats
While this method offers resuscitated functionality, there are some caveats:
Despite these limitations, it's clear that with a little ingenuity, template literals can transcend their conventional confines and become truly reusable.
The above is the detailed content of Can Template Literals Be Truly Reused?. For more information, please follow other related articles on the PHP Chinese website!