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.
Template without placeholder
<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>
let template = document.getElementById('template-id');
let templateContent = template.content;
document.body.appendChild(templateContent);
// the second append has no effect
document.body.appendChild(templateContent);
Example from the specification 1)
<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.
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);
See HTML Slot - A step by step on how to create a Template Placeholder