示例工程 44-slots-templates

44-slots-templates/demo-02-template/index.html

html · 2.1 KB

运行:模板克隆演示

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>模板克隆演示</title>
    <style>
      body { margin: 0; padding: 32px; background: #f8fafc; color: #0f172a; font-family: system-ui, sans-serif; line-height: 1.7; }
      .box { max-width: 720px; margin-bottom: 16px; padding: 18px; border: 1px solid #e2e8f0; border-radius: 12px; background: #fff; }
      h1 { margin: 0 0 16px; font-size: 28px; }
      h2 { margin: 0 0 8px; font-size: 17px; }
      p { margin: 0 0 10px; color: #334155; }
      ul { margin: 8px 0 0; padding: 0; list-style: none; }
      li { display: flex; justify-content: space-between; gap: 10px; padding: 8px 10px; border-bottom: 1px solid #e2e8f0; font-size: 14px; }
      li span { color: #64748b; }
      code { padding: 1px 5px; border-radius: 4px; background: #f1f5f9; font-family: ui-monospace, monospace; }
    </style>
  </head>
  <body>
    <h1>模板克隆</h1>

    <div class="box">
      <h2>一份模板,三行数据</h2>
      <p>模板只在解析时处理一次,脚本按数据克隆并填文本。</p>
      <ul id="list"></ul>
    </div>

    <div class="box">
      <h2>模板不会渲染</h2>
      <p><code>&lt;template&gt;</code> 内的内容不属于文档,除非被克隆插入。</p>
    </div>

    <template id="row-tpl">
      <li>
        <strong data-name></strong>
        <span data-role></span>
      </li>
    </template>

    <script>
      const rows = [
        { name: "林小满", role: "维护者" },
        { name: "周野", role: "审校" },
        { name: "陈一", role: "设计" },
      ];
      const tpl = document.getElementById("row-tpl");
      const list = document.getElementById("list");
      const fragment = document.createDocumentFragment();
      rows.forEach((row) => {
        const node = tpl.content.cloneNode(true);
        node.querySelector("[data-name]").textContent = row.name;
        node.querySelector("[data-role]").textContent = row.role;
        fragment.append(node);
      });
      list.append(fragment);
    </script>
  </body>
</html>