Lesson 44 of 55 · HTML
The `<template>` Element – Declaring Inert Template Content
Duration: 9 min
The <template> Element – Inert Markup for Cloning
<template> stores markup that isn’t rendered until you clone it via JavaScript.
<template id='cardTemplate'>
<article class='card'>
<h3></h3>
<p></p>
<a href='' class='more'>Read more</a>
</article>
</template>
<div id='grid'></div>
<script>
const data = [
{ title: 'Project One', desc: 'Brief description', url: '#1' },
{ title: 'Project Two', desc: 'Brief description', url: '#2' }
];
const tmpl = document.getElementById('cardTemplate').content;
const grid = document.getElementById('grid');
data.forEach(item => {
const clone = document.importNode(tmpl, true);
clone.querySelector('h3').textContent = item.title;
clone.querySelector('p').textContent = item.desc;
clone.querySelector('a').href = item.url;
grid.appendChild(clone);
});
</script>
Benefits
- Zero‑render cost – Content inside
<template>isn’t parsed into the DOM until you explicitly clone it. - Reusable – Keep HTML DRY and separate data from markup.
- Safe – Anything inside
<template>cannot execute scripts or load resources until instantiated.
Quick checklist for <template>
- Template stored in a
<template id='…'>element? ✅ - Cloned via
document.importNodewithdeep:true? ✅ - Scripts or heavy resources not loaded before cloning? ✅
- Used for repeated UI components (cards, list items)? ✅
- Fallback content provided for browsers without
<template>(rare)? ✅
Tip: Combine
<template>with Web Components to build fully encapsulated, reusable UI patterns.