Table of Contents
What the template tag does
Basic usage example
Key points when working with templates
Advanced: Pre-fill template with data attributes or slots
Home Web Front-end H5 Tutorial How to use the HTML5 template tag

How to use the HTML5 template tag

Aug 31, 2025 am 08:23 AM
html5

The HTML5 <template> tag stores inert, reusable HTML content that can be cloned with JavaScript; it remains unrendered until programmatically inserted, making it ideal for dynamically generating elements like product cards without reloading or hardcoding, and it supports advanced features like data attributes and slots for flexible, organized, and performant DOM manipulation.

How to use the HTML5 template tag

The HTML5 <template></template> tag is a handy way to store HTML content that you don’t want to render immediately when the page loads. Instead, you can clone and insert this content later using JavaScript. It's perfect for dynamically adding elements like cards, forms, or list items without hardcoding them repeatedly or fetching HTML from external sources.

Here’s how to use it effectively.

What the template tag does

The <template></template> element holds content that is:

  • Not rendered on the page when the document loads.
  • Parsed but inert — scripts inside don’t run, images don’t load, custom elements aren’t upgraded.
  • Available for cloning via JavaScript when needed.

This makes it ideal for reusable UI components created on the fly.

Basic usage example

Let’s say you want to dynamically add product cards to a page.

<template id="product-card-template">
  <div class="product-card">
    <h3 class="product-title"></h3>
    <p class="product-price"></p>
    <button>Buy Now</button>
  </div>
</template>

<div id="product-container"></div>

Now use JavaScript to clone the template and populate it:

// Get the template and container
const template = document.getElementById('product-card-template');
const container = document.getElementById('product-container');

// Function to add a new product
function addProduct(title, price) {
  // Clone the template content
  const clone = document.importNode(template.content, true);

  // Update the cloned elements
  clone.querySelector('.product-title').textContent = title;
  clone.querySelector('.product-price').textContent = `$${price}`;

  // Append to the container
  container.appendChild(clone);
}

// Add some products
addProduct('Laptop', 999);
addProduct('Mouse', 25);

Now two product cards appear — created from the template.

Key points when working with templates

  • Use document.importNode() or template.content.cloneNode()
    Always clone the .content of the template (which is a DocumentFragment). This avoids modifying the original template.

  • Deep clone with true
    Pass true as the second argument to importNode() or cloneNode() to ensure all child nodes are copied.

  • Templates are not limited to one use
    You can use the same template to create multiple instances across your app.

  • Works well with shadow DOM and web components
    Templates are often used inside custom elements to define internal structure.

  • No need to hide templates with CSS
    The content inside <template> is automatically not displayed — no display: none required.

Advanced: Pre-fill template with data attributes or slots

You can design more flexible templates using data-* attributes or the <slot> element (especially useful with web components).

<template id="user-card">
  <div class="user-card">
    <img src="" alt="" class="avatar">
    <h2 class="name"></h2>
    <span class="role" data-role></span>
  </div>
</template>

Then fill in values including src, alt, and data attributes as needed in JavaScript.


Basically, the <template></template> tag gives you a clean, performant way to manage reusable HTML. It’s not flashy, but it keeps your DOM clean and your dynamic content organized.

The above is the detailed content of How to use the HTML5 template tag. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is Forest Protocol (FOREST currency)? How about it? FOREST token economic model and market prospect analysis What is Forest Protocol (FOREST currency)? How about it? FOREST token economic model and market prospect analysis Sep 05, 2025 am 09:09 AM

Catalog ForestProtocol's birth background The innovative technology architecture of interactive tokens (Playable Tokens) CampaignOS: Turn tokens into "playable products" Launchpad and AMM: No curves, no migration, flywheels and fees: Convert usage and revenue into repurchase and destroy CampaignOS's role and value Launchpad and AMM mechanism $FOREST's token economic model Where the value of $FOREST comes from the latest price and market outlook roadmap: From template

What is the placeholder attribute's purpose in HTML5? What is the placeholder attribute's purpose in HTML5? Aug 31, 2025 am 06:58 AM

Theplaceholderattributeprovidesashorthintininputfieldsthatdisappearswhentypingbegins;1.Itisusedinandelementstoshowexampletextlike"Enteryouremail";2.Thehintisdisplayedonlywhenthefieldisemptyandstyledfaintlybybrowsers;3.Itdoesnotreplacetheele

How to use the HTML5 template tag How to use the HTML5 template tag Aug 31, 2025 am 08:23 AM

TheHTML5tagstoresinert,reusableHTMLcontentthatcanbeclonedwithJavaScript;itremainsunrendereduntilprogrammaticallyinserted,makingitidealfordynamicallygeneratingelementslikeproductcardswithoutreloadingorhardcoding,anditsupportsadvancedfeatureslikedataat

How does Content Security Policy (CSP) work with HTML5? How does Content Security Policy (CSP) work with HTML5? Aug 30, 2025 am 01:29 AM

CSPenhancesHTML5securitybydefiningtrustedcontentsourcestopreventXSS,clickjacking,andcodeinjection.1.Itrestrictsinlinescriptsandstylesbyblockingthemunless'unsafe-inline',nonces,orhashesareused.2.Itcontrolsexternalresourcesviadirectiveslikescript-src,i

How to properly use the  element in HTML5? How to properly use the element in HTML5? Sep 17, 2025 am 06:33 AM

ThetimeelementinHTML5representsdatesandtimesinamachine-readableformat,enhancingaccessibilityandSEO;usethedatetimeattributewithISO-formattedvaluestoprovidesemanticmeaning,especiallyforhuman-friendlytextordurations,ensuringconsistentinterpretationbymac

How to implement HTML5 drag and drop How to implement HTML5 drag and drop Sep 02, 2025 am 04:58 AM

To implement HTML5 drag and drop, you must first set the draggable="true" of the element, then use e.dataTransfer.setData() to define the drag data through the dragstart event, and listen to the dragover and drop events on the drop target. The dragover must call e.preventDefault() to allow placement. Finally, the data is obtained and operations are performed through getData() in the drop event. The entire process needs to correctly handle data delivery and default behavior, and fully implement the drag and drop function of element.

How to use ARIA roles for accessibility in HTML5? How to use ARIA roles for accessibility in HTML5? Sep 21, 2025 am 04:41 AM

ARIAenhanceswebaccessibilitybyaddingsemanticmeaningtoelementswhennativeHTMLisinsufficient.UseARIAroleslikerole="button",aria-expanded,andaria-labelforcustomcomponentsordynamiccontent,butalwaysprefernativeHTMLelementssuchasbuttonornav.Update

How to create a full-screen video background with HTML5 How to create a full-screen video background with HTML5 Aug 30, 2025 am 07:44 AM

To create a full-screen video background, you need to use HTML5 tags and combine CSS to achieve responsive coverage. First, add elements with autoplay, muted, and loop attributes to HTML to ensure automatic loop playback and compatibility. Then, set position:fixed, width and height to 100%, object-fit:cover to fill the viewport and crop it to avoid deformation. At the same time, set z-index:-1 to place the video at the bottom of the content. In order to improve performance and compatibility, static images should be provided as a downgrade fallback, optimize the video format H.264 encoded MP4 and control the file size. For mobile devices, you can use media

See all articles