"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 Template Literals Be Truly Reused?

Can Template Literals Be Truly Reused?

Published on 2024-11-07
Browse:464

Can Template Literals Be Truly Reused?

Template Literals: Resuscitating Reuse

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:

  • Runtime interpolation: Variables are filled in dynamically, like in traditional template engines.
  • Fragmentation: Templates can be stored in separate files or obtained dynamically.
  • Dynamic creation: Templates can be constructed and evaluated on the fly.

Addressing Caveats

While this method offers resuscitated functionality, there are some caveats:

  • Limited JavaScript: Inline JavaScript logic is not possible due to late interpolation.
  • Template tags: Template tags become challenging to implement.

Despite these limitations, it's clear that with a little ingenuity, template literals can transcend their conventional confines and become truly reusable.

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