Clean Markup

Reusable Markup Fragments with the Native HTML template Element

Reusable Markup Fragments with the Native HTML template Element

Modern single-page applications often require rendering repetitive markup patterns such as comment cards, search result rows, or table items. While developers frequently generate these items by concatenating innerHTML strings, string interpolation introduces security vulnerabilities like cross-site scripting (XSS) and forces the browser parser to re-evaluate raw strings repeatedly.

The <template> HTML element holds client-side content that is not rendered when the page is loaded, but can be instantiated dynamically at runtime using JavaScript.

Example

We declare the template structure directly within our semantic HTML markup:

<template id="comment-card-template">
  <article class="comment-card">
    <header class="comment-header">
      <h3 class="author-name"></h3>
      <time class="comment-time"></time>
    </header>
    <p class="comment-body"></p>
  </article>
</template>

<section id="comments-container" class="comments-feed"></section>

Implementation

The content of a <template> is stored in a DocumentFragment. When instantiating it, we clone the fragment using document.importNode or template.content.cloneNode(true):

const template = document.getElementById('comment-card-template');
const container = document.getElementById('comments-container');

function renderComment(author, timestamp, text) {
  // Clone the template content (deep copy)
  const clone = template.content.cloneNode(true);

  // Populate data using safe textContent to prevent XSS
  clone.querySelector('.author-name').textContent = author;
  clone.querySelector('.comment-time').textContent = timestamp;
  clone.querySelector('.comment-body').textContent = text;

  // Append cloned node to live DOM
  container.appendChild(clone);
}

renderComment('Ada Lovelace', '22 Dec 2020', 'Semantic markup guarantees long-term maintainability.');

Main Point: The native <template> element keeps HTML structure declarative in markup while allowing fast, safe DOM node cloning without template compilation overhead.

Credits

Photo by Ksenia Chernaya on Unsplash

← Home