liveBook · Manning

Template content property

As explained in Web Components in Action

The template content property exposes the template element's stored markup as a document fragment.

The template content property exposes a <template> element’s stored markup as a document fragment. Template markup remains absent from the rendered page until you explicitly clone and append that fragment. section 7.2

Use the property to:

  • Select a template with document.getElementById(). section 7.2
  • Clone template.content with cloneNode(true), preserving its nested markup. section 7.2
  • Append the clone to the document; the resulting elements move out of the fragment. section 7.2

Rendering a template

const template = document.getElementById('button'); const clone = template.content.cloneNode(true); document.body.appendChild(clone); section 7.2

Listing 7.5. Adding a few templates to a page
<html>
<body>
   <template id="button">                            #1
       <button>Click Me</button>
       <p>
           This is a template with a button
       </p>
   </template>

   <template id="textfield">
       <label>Enter</label>
       <input type="text">
       <p>
           This is a template with a text input
       </p>
   </template>

   <template id="list">
       <ul>
           <li>Item 1</li>
           <li>Item 2</li>
           <li>Item 3</li>
           <li>Item 4</li>
       </ul>
   </template>

<script>
   const template =                                  #2
      document.getElementById('button');
   const clone =                                     #3
      template.content.cloneNode(true);
   document.body.appendChild(clone);                 #4
</script>

</body>
</html>

Compare several stored templates with the script that reads one template’s content and adds its clone to the page. section 7.2

How Web Components in Action covers it

How deep it goes
Explains fragments, cloning, insertion, and repeated rendering, while stopping short of broader template design.
Examples
Uses hidden paragraph markup, several named templates, and repeated button-template cloning.
What it assumes
Assumes basic HTML and JavaScript DOM access while introducing document fragments from first principles.
What you can do after
Apply it via DOM APIs to clone template markup and append rendered instances to a page.
How it connects
Connects the content property to template elements, document fragments, the DOM, cloneNode, and appendChild.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.