Reusability conundrum in ES6 Template Literals
The primary concern raised in this discussion revolves around the presumed lack of reusability in ES6 template literals. Conventional demonstrations emphasize substitutions at declaration time, disallowing runtime modification.
Solution: Leveraging the Function Constructor
To address this issue, a viable solution emerges in the form of the Function constructor. This approach involves converting the template string into a function.
Consider the following snippet:
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));
By invoking this function, you can generate the desired string while possessing the flexibility to modify variables at runtime.
Benefits of this approach:
Potential drawbacks:
In summary, while ES6 template literals inherently lack true reusability, employing the Function constructor offers a workaround that emulates the desired behavior of creating and modifying templates at runtime.
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