Challenge:
Developers often find ES6 template literals invaluable for string interpolation. However, a common frustration arises when attempting to reuse or evaluate these literals at runtime. It seems like the substitutions must always be done at declaration time, limiting their practicality as templates.
Solution:
To overcome this limitation and create reusable template literals that can be reused and evaluated dynamically, we must introduce an intermediary stage.
Using the Function Constructor:
The key to reusability lies in utilizing the Function constructor to wrap the template string. By doing so, we essentially transform the template into a JavaScript function that can be invoked later with specific variable values.
<code class="js">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)); // Output: "Hello world!"</code>
In this example, the fillTemplate function takes both the template string and a variable object as arguments. It wraps the template in a function, then returns the result of calling that function with the given variable values. This allows us to evaluate the template dynamically, plugging in different variable values each time.
Additional Considerations:
While this method provides a workaround for the reusability issue, it also introduces potential limitations.
Alternative Approaches:
Some may prefer to explore alternative template engine libraries that provide a more comprehensive solution for reusable and runtime-evaluated templates.
The above is the detailed content of How to Create Reusable ES6 Template Literals for Dynamic Evaluation?. For more information, please follow other related articles on the PHP Chinese website!