"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can ES6 Template Literals be Truly Reusable?

Can ES6 Template Literals be Truly Reusable?

Published on 2024-11-08
Browse:764

Can ES6 Template Literals be Truly Reusable?

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:

  • Enables runtime substitution of template values
  • Facilitates interpolation from external sources, such as files
  • Allows for dynamic string manipulation

Potential drawbacks:

  • Template tags may require additional implementation effort
  • Inline JavaScript logic within templates is not supported due to late interpolation
  • Memory overhead associated with function creation for each template use

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.

Latest tutorial More>

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