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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3