CodeBlanks Logo Icon CodeBlanks

Template element

HTML course · Advanced · Lesson 35/56

Write reusable HTML templates with <template>.

What is the template element?

The <template> tag is an HTML skeleton that stays in the DOM but never shows on the page. Its content is not rendered: the browser parses it but does not paint it. You can reuse the same structure again and again.

You can define a list row, a card or a modal skeleton. With JavaScript you reach template.content, clone it and add the copy to the page. That makes template the backbone of repeating UI parts.

What can live inside a template?

Inside a <template> you can place anything a normal document accepts: <div>, <h2>, <p>, <img>, even <style> and <script>. The browser parses them but does not run them.

The content only comes alive when you clone template.content and add it to the page. This makes a card or row skeleton perfect for reuse: write once, paint many times.

Cloning a template

To use a template you first reach its template.content property. This is a DocumentFragment holding the inner nodes. You call cloneNode(true) for a deep copy and add it somewhere else.

That way the same skeleton can power dozens of instances, each with different data. Instead of writing raw HTML again, you clone the template: cleaner and faster.

Exercise Write a template with content

Add a <template> to body. Inside it put an <h2> and a <p>. The <h2> text should be Title, the <p> text Description.

Show example solution
<body>
  <template>
    <h2>Title</h2>
    <p>Description.</p>
  </template>
</body>

Test yourself

  1. What is the most distinctive feature of <template>?

    • Its content is not rendered but kept in the DOM.
    • It adds its content to the page automatically.
    • It only works inside JavaScript files.
    • It accepts only text, no other tags.
    Show answer

    Its content is not rendered but kept in the DOM. — Correct. The template's content is not shown but is ready to be cloned.

  2. Close the template tag

    <template>
      <h2>News____
    </template>
    Show answer
    <template>
      <h2>News</h2>
    </template>
  3. Match the template terms

    template
    HTML template tag
    inert
    not rendered on the page
    content
    template's DOM root
    cloneNode
    clones the template

All lessons in Advanced