Want to keep a component’s markup as HTML instead of putting it in a JavaScript string? A <template> can hold that markup until the component needs it. Unlike an ordinary paragraph placed on a page, a paragraph inside <template> does not appear immediately. The markup is available through the element’s content property as a document fragment. section 7.0 section 7.2
A document fragment can hold several nodes without adding a wrapper element to the page. Appending the fragment moves its children into the destination, leaving the fragment empty. That matters for templates: clone template.content before appending if you want to use the same markup again. 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>
The button, text-field, and list templates remain available in the page. The script selects the button template, clones its content, and appends the clone to the body. section 7.2
Swap a component’s layout
Give each layout a template ID. When a custom element’s observed layout attribute changes, clear the element, find the matching template with document.getElementById(newvalue), then append template.content.cloneNode(true). A separate drop-down can change the attribute. Keep that menu outside the element in this version: clearing the element’s innerHTML would otherwise remove it too. section 7.3
Templates need not live in the main page. One variation requests an HTML file containing the templates, places the response in a container inside the component, and clones the selected layout into a separate display container. Clear only the display container when layouts change, so the loaded templates survive. Check that the template container exists before using it: the attribute callback may run before the component’s connection callback. section 7.4
Templates are an option, not a requirement for every Web Component. They are especially useful when many interchangeable HTML-and-CSS layouts should remain editable as HTML. An older HTML Imports example also stores component markup in a template, but HTML Imports are no longer on a standards track; the template technique does not depend on adopting Imports. section 7.6 section 7.1


