HTML - Template Element (Scripted HTML Fragment)

About

The template element is an HTML element that supports templating.

It creates:

A template fragment is not rendered, but stored until it is instantiated via JavaScript

When use in conjunction with a custom element and the shadow dom, the code created is called a web component.

Example

Basic

Template without placeholder

  • Template
<template id="template-id">
  <style>
    p {
      color: white;
      background-color: #666;
      padding: 5px;
    }
  </style>
  <h1>Template</h1>
  <p>A template that appears only if Javascript add it to the page</p>
</template>
  • Javascript will add the template content
let template = document.getElementById('template-id');
let templateContent = template.content;
document.body.appendChild(templateContent);
// the second append has no effect
document.body.appendChild(templateContent);
  • Result:

Loop

Example from the specification

  • The template.
<template id="template"><p>Smile!</p></template>

The p element is not a child of the template in the DOM; it is a child of the DocumentFragment returned by the template element's content IDL attribute.

  • The javascript.
   let num = 3;
   const fragment = document.getElementById('template').content.cloneNode(true);
   while (num-- > 1) {
     fragment.firstChild.before(fragment.firstChild.cloneNode(true));
     fragment.firstChild.textContent += fragment.lastChild.textContent;
   }
   document.body.appendChild(fragment);
  • The result:

Slot

Documentation / Reference


Powered by ComboStrap