<template>

The <template> element in HTML enables the creation of reusable HTML snippets that are inactive and not displayed until triggered by JavaScript. This feature facilitates modular and dynamic content generation within web pages.

<template> Tag

The <template> tag in HTML defines a block of HTML content that is not displayed when the page initially loads. It is stored for future use, often with JavaScript, and remains hidden until added to the document's DOM.

Syntax

index.html
<template>
  <!-- HTML content here -->
</template>

Examples

  • Generating table rows
  • Implementing a declarative shadow DOM

Generating Table Rows

First, we start with the HTML portion of the example.

UPC_Code Product_Name
index.html
<table id="producttable">
  <thead>
    <tr>
      <td>UPC_Code</td>
      <td>Product_Name</td>
    </tr>
  </thead>
  <tbody>
    <!-- Existing data could optionally be included here -->
  </tbody>
</table>
<template id="productrow">
  <tr>
    <td class="record"></td>
    <td></td>
  </tr>
</template>

Implementing a Declarative Shadow DOM

This example includes a hidden warning for browsers that lack support. Two <article> elements are used:

  • The first <style> applies styles globally.
  • The second <style> is scoped to the shadow root created by the shadowrootmode attribute.

Attributes

  • This element supports all standard attributes.
  • shadowrootmode: Specifies how the shadow root is created for a parent element.
    • open: Makes the shadow root DOM accessible via JavaScript.
    • closed: Keeps the shadow root DOM hidden from JavaScript.
  • shadowrootclonable: Allows the shadow root to be cloned along with its host element.
  • shadowrootdelegatesfocus: Enables focus to be directed to the first focusable element within the shadow DOM.
  • shadowrootserializable (Experimental): Allows the shadow root to be serialized using certain methods.

See Also

  • part and exportparts HTML attributes
  • <slot> HTML element
  • ShadowRoot interface
  • Using templates and slots
  • CSS scoping module
  • Declarative Shadow DOM (with HTML) in Using Shadow DOM

Conclusion

The <template> tag in HTML allows developers to define reusable content that remains hidden until needed, often for dynamic updates with JavaScript. It is commonly used for tasks like generating table rows or implementing shadow DOM components. The content inside the <template> tag is stored for future use and does not display when the page loads.