The <template> Tag in HTML
The <template> tag in HTML is used to define reusable fragments of HTML that are not displayed in the browser when the page loads. Instead, the content inside a <template> is stored and can later be cloned and inserted into the DOM using JavaScript. This makes it useful for creating dynamic UI components without rendering hidden elements upfront.
When you want to define reusable HTML snippets that can be inserted dynamically.
For rendering UI components like cards, modals, or lists without duplicating code.
When working with JavaScript frameworks or vanilla JS that manipulate DOM nodes.
To keep HTML structure clean while avoiding hidden elements in the DOM.
You're building a simple todo list. The designer gives you an <li> template for each item. Show me how you'd use <template> to stamp out new items when the user clicks 'Add'.
A teammate wrote <template id='t'><div>{{name}}</div></template> and does t.innerHTML = t.innerHTML.replace('{{name}}', 'Alice'). What's wrong with that approach and how would you fix it using the template API?
We're rendering a table with 500 rows from a <template>. Users report jank when sorting. Walk me through how you'd profile this and what template-specific optimizations you'd try.
A component uses <template> + Shadow DOM for encapsulation. Styles defined inside the template aren't applying. What are the likely causes and how do you verify the style scoping is working?
Design a reusable <data-grid> web component that accepts a <template> slot for custom row rendering. How do you handle type-safe props passed to the row template, and what's your strategy for efficient re-renders when only sort order changes?
During SSR hydration, your <template>-based components flicker because the server HTML doesn't match the client-stamped DOM. How do you architect the template system to support seamless hydration without duplicating template logic?
Your org has 12 micro-frontends each with their own <template> patterns. You're tasked with creating a shared template registry that enforces versioning, schema validation, and tree-shaking. What's the governance model and how do you handle breaking changes across teams?
A legacy codebase uses string-based templating (Handlebars) everywhere. You're leading a migration to native <template> + web components. Outline the incremental strategy, risk mitigation for partial adoption, and how you measure performance regression during the transition.