模板標籤

Frontend SELF TW
等級 10 , 課堂 5
開放

5.1 標籤 <template>

HTML中的<template>標籤讓開發者可以定義HTML代碼片段, 這些片段在頁面加載時不會顯示,但可以通過JavaScript後續使用。這特別適合用於 動態創建和插入內容,比如列表項、產品卡片和其他重複結構。

<template>元素用來儲存HTML代碼,在頁面上不會立刻顯示。 <template>中的內容在頁面加載時不會被瀏覽器渲染,但可以通過DOM (Document Object Model)訪問,並透過JavaScript進行克隆和插入。

語法:

HTML
    
      <template>
        <!-- 模板內容 -->
      </template>
    
  

<template>標籤的主要特點

  1. 隱藏內容<template>標籤的內容在頁面加載時不會顯示。
  2. JavaScript使用<template>標籤的內容可以通過JavaScript克隆並插入到DOM中。
  3. 延遲加載:允許僅在需要時加載和顯示內容,這可以提升頁面效能。

<template>標籤的使用範例

在這個例子中,當按下"Add Item"按鈕時會產生一個新的列表項,並添加到<ul>列表中。 新的列表項模板在<template>標籤內定義。

HTML
    
      <button id="addButton">Add Item</button>
      <ul id="itemList"></ul>
      <template id="itemTemplate">
        <li class="item">This is a new item</li>
      </template>
    
  
JavaScript
    
// 獲取將要使用的DOM元素的引用
const addButton = document.getElementById('addButton'); // "添加"按鈕
const itemList = document.getElementById('itemList'); // 添加元素的列表
const itemTemplate = document.getElementById('itemTemplate'); // 列表項模板

// 給"添加"按鈕添加事件處理器
addButton.addEventListener('click', () => {
  // 克隆列表項模板的內容
  const newItem = itemTemplate.content.cloneNode(true); // true表示深度克隆(包括所有子元素)

  // 將新項目添加到列表中
  itemList.appendChild(newItem); 
});
    
  

5.2 範例: 商品卡片生成

<template>和JavaScript,比如可以生成商品卡片列表。

<template>標籤的使用範例:

HTML
    
      <h1>商品列表</h1>
      <div id="productList"></div>
      <template id="productTemplate">
        <div class="item">
          <h2 class="title"></h2>
          <p class="description"></p>
          <span class="price"></span>
        </div>
      </template>
    
  
JavaScript
    
// 等待DOM完全加載後執行腳本
document.addEventListener('DOMContentLoaded', () => {
  // 商品數據數組
  const products = [
    { title: '商品 1', description: '商品 1 的描述', price: '100 美元' },
    { title: '商品 2', description: '商品 2 的描述', price: '200 美元' },
    { title: '商品 3', description: '商品 3 的描述', price: '300 美元' },
  ];

  // 獲取DOM中的元素引用
  const productList = document.getElementById('productList'); // 產品列表的容器
  const template = document.getElementById('productTemplate').content; // 產品元素的模板

  // 遍歷商品數組並為每個商品創建列表元素
  products.forEach(product => {
    // 克隆產品模板
    const clone = document.importNode(template, true); // true - 深度克隆

    // 填充克隆模板內的數據
    clone.querySelector('.title').textContent = product.title;
    clone.querySelector('.description').textContent = product.description;
    clone.querySelector('.price').textContent = product.price;

    // 將填充的模板添加到產品列表中
    productList.appendChild(clone);
  });
});
    
  

解釋

  • 標籤<template>:包含頁面加載時不會顯示的HTML代碼。
  • 方法document.importNode(template, true):克隆模板的內容。
  • 方法querySelectortextContent:用於在插入到文檔之前修改克隆模板的內容。

5.3 <template>標籤的優勢

提升效能

使用模板可以預先加載稍後將使用的HTML代碼。這可以 改善頁面效能,因為模板內容不會渲染,也不會影響頁面的初始加載。

簡化動態內容

模板使動態內容的創建變得簡單。與其用JavaScript程式生成HTML代碼, 不如直接克隆和修改預先準備的模板。

方便與可讀性

模板使代碼更具可讀性和結構,因為重複元素的HTML代碼可以 獨立儲存,而非插入到JavaScript中。

例子:條件顯示內容:

HTML
    
      <h1>操作結果</h1>
      <div id="messageContainer"></div>

      <template id="messageTemplate">
        <div class="message">
          <p class="content"></p>
        </div>
      </template>
    
  
JavaScript
    
document.addEventListener('DOMContentLoaded', () => {
  // 獲取DOM中的元素引用
  const messageContainer = document.getElementById('messageContainer'); // 消息的容器
  const template = document.getElementById('messageTemplate').content; // 消息模板

  // 顯示消息的函數
  function showMessage(type, text) {
    // 克隆消息模板
    const clone = document.importNode(template, true); // true - 深度克隆

    // 獲取克隆內的消息元素引用
    const messageDiv = clone.querySelector('.message');

    // 添加對應消息類型的類(success或error)
    messageDiv.classList.add(type);

    // 設置消息內容
    messageDiv.querySelector('.content').textContent = text;

    // 將消息添加到容器中
    messageContainer.appendChild(clone);
  }

  // 調用函數顯示消息
  showMessage('success', '操作成功完成!');
  showMessage('error', '操作時發生錯誤。');
});
    
  

解釋:

  • 函數showMessage():接收消息類型(成功或錯誤)和消息內容,克隆模板並將其添加到消息容器。
  • .success.error:根據消息類型應用於克隆模板以進行樣式化。
1
Опрос
HTML5語義標籤,  10 уровень,  5 лекция
недоступен
HTML5語義標籤
HTML5語義標籤
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION