[Javascript] HTML Template Interpolation

The basic interpolatefunction we can create:

function interpolate(str, params) {
      let names = Object.keys(params); // ["title", "description"]
      let values = Object.values(params); //    ["Hello", "World"]
      const body = `return \`${str}\`;`; // return `<h1>${title}</h1><p>${description}</p>`;
      return new Function(...names, body)(...values);

      /*(function(titile, description) {
        return `<h1>${title}</h1><p>${description}</p>`;
      })("Hello", "World");  
      */
    }
    const html = "<h1>${title}</h1><p>${description}</p>";
    const finalHtml = interpolcate(html, {
      title: "Hello",
      description: "World",
    });

 

Example:

For a web component, we have a template:

    <template id="cart-item-template">
      <li>
        <p class="qty"></p>
        <p class="name"></p>
        <p class="price"></p>
        <p class="toolbar">
          <a href="#" class="delete-button"> 🗑️ </a>
        </p>
      </li>
    </template>

And javascript part:

import { removeFromCart } from "../services/Order.js";

export default class CartItem extends HTMLElement {
  constructor() {
    super();
  }

  connectedCallback() {
    const item = JSON.parse(this.dataset.item);
    this.innerHTML = ""; // Clear the element

    const template = document.getElementById("cart-item-template");
    const content = template.content.cloneNode(true);
      
    this.appendChild(content);
    this.querySelector(".qty").textContent = `${item.quantity}x`;
    this.querySelector(".name").textContent = item.product.name;
    this.querySelector(".price").textContent = `$${item.product.price.toFixed(
      2
    )}`;
    this.querySelector("a.delete-button").addEventListener("click", (event) => {
      removeFromCart(item.product.id);
    });
  }
}

customElements.define("cart-item", CartItem);

 

Our target is using template syntax such as Angular or React in our code:

    <template id="cart-item-template">
      <li>
        <p class="qty">${qty}</p>
        <p class="name">${name}</p>
        <p class="price">${price}</p>
        <p class="toolbar">
          <a href="#" class="delete-button"> 🗑️ </a>
        </p>
      </li>
    </template>

Javascript code:

import { removeFromCart } from "../services/Order.js";

export default class CartItem extends HTMLElement {
  constructor() {
    super();
  }

  connectedCallback() {
    const item = JSON.parse(this.dataset.item);
    this.innerHTML = ""; // Clear the element

    const template = document.getElementById("cart-item-template");
    const content = template.content.cloneNode(true);

    // Interpolate the template with the item data
    function interpolate(str, params) {
      let names = Object.keys(params);
      let values = Object.values(params);
      const body = `return \`${str}\`;`;
      return new Function(...names, body)(...values);
    }

    this.innerHTML = interpolate(template.innerHTML, {
      qty: `${item.quantity}x`,
      name: item.product.name,
      price: `${item.product.price.toFixed(2)}`,
    });

    this.querySelector("a.delete-button").addEventListener("click", (event) => {
      removeFromCart(item.product.id);
    });
  }
}

customElements.define("cart-item", CartItem);

 

posted @   Zhentiw  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-08-20 [Supabase] Use Triggers to Automatically Update Your Supabase Tables
2021-08-20 [SAA + SAP] 31. Migrations
2020-08-20 [React] Using react-styleguidist for Component demo
2019-08-20 [GraphQL] Query Lists of Multiple Types using a Union in GraphQL
2019-08-20 [GraphQL] Query GraphQL Interface Types in GraphQL Playground
2019-08-20 [GraphQL] Reuse GraphQL Selection Sets with Fragments
2019-08-20 [GraphQL] Use an Input Type to Create an Account with a GraphQL Mutation
点击右上角即可分享
微信分享提示