Home > Web Front-end > JS Tutorial > body text

Can Template Literals Be Truly Reused?

Patricia Arquette
Release: 2024-11-02 13:02:02
Original
847 people have browsed it

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!
Copy after login

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.

The above is the detailed content of Can Template Literals Be Truly Reused?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!