HTML <template> Tag: Usage, Attributes and Real-World Examples

By Cristian G. Guasch •  Updated: 09/25/23 •  9 min read

I’m diving into the world of HTML today, specifically focusing on the <template> tag. This powerful yet often overlooked element can revolutionize how you write your code, making it cleaner and more efficient. It’s like a secret weapon in the arsenal of any web developer.

The <template> tag is used to hold client-side content that you don’t want to render immediately when a page loads. Instead, it waits patiently until called upon by Javascript. The beauty of this feature? You’re not loading unnecessary data until it’s truly needed, optimizing your website’s performance.

Let me guide you through its usage, attributes and examples that’ll shed light on this underused HTML gem. By mastering the <template> tag, you’ll be equipped with another tool that’ll make your coding endeavors smoother and faster!

Understanding the HTML <template> Tag

Diving right into the heart of HTML, let’s shed some light on a lesser-known but incredibly useful element – the <template> tag. Brought to life with HTML5, this little gem allows us to declare fragments of HTML that can be cloned and inserted in the document by JavaScript.

So, what makes it special? Well, its content is inactive/inert when the page loads and won’t render until activated via JavaScript. This means it doesn’t interact with the rest of your web page’s DOM till called upon. It’s like having an ace up your sleeve for later use!

Consider this simple example:

<template id="myTemplate">
   <p>Hello, World!</p>
</template>

<script>
  var temp = document.getElementsByTagName("template")[0];
  var clon = temp.content.cloneNode(true);
  document.body.appendChild(clon);
</script>

In this code snippet, we first define a template containing a paragraph element. Then using JavaScript, we fetch our template, clone its content and finally append it to our body element.

Now let’s talk about attributes – surprisingly enough though, there aren’t any specific ones for <template>! However standard global attributes apply here as well – id, class, style among others.

One common mistake tends to be attempting to manipulate the contents of <template> directly without cloning them first. Remember folks: inert till activated! Here’s an example of such an incorrect usage:

<template id="wrongTemplate">
    <p id="para">Hello again!</p>
</template>

<script>
    document.getElementById("para").innerText = "Uh oh...";
</script>

This script will throw an error because you’re trying to access elements within a template before they’ve been activated or rendered on your webpage.

Learning how to effectively use the <template> tag opens up a world of efficient, dynamic web design. Give it a whirl and see how your HTML game changes for the better!
Diving right into it, the HTML <template> tag doesn’t have any specific attributes of its own. It’s like a chameleon blending seamlessly in its environment. However, it does play well with global attributes – those that are common to all HTML tags.

You’re probably wondering what these global attributes are. They include ‘class’, ‘id’, ‘style’, ‘title’ and so forth. These may not be unique to our humble <template> tag but they sure do boost its functionality. For instance, adding an ‘id’ attribute can help you single out a particular template element in your JavaScript code.

Let’s take a look at an example:

<template id="myTemplate">
  <p>This is my first template!</p>
</template>

In this snippet, I’ve used the ‘id’ attribute to identify my <template>. Now I can easily access it in my JavaScript file using the getElementById method.

But wait, there’s more! The HTML <template> tag also plays nicely with event attributes such as onclick, onload etc. These let you trigger certain actions when an event occurs on your template element.

Here’s another example for you:

<button onclick="loadTemplate()">Click me!</button>

<template id="mySecondTemplate">
  ...
</template>

<script>
function loadTemplate() {
  var tempContent = document.getElementById("mySecondTemplate").content;
  document.body.appendChild(tempContent);
}
</script>

In this case, clicking the button triggers the loadTemplate function which fetches the content inside my template and appends it to the body of my web page.

So while our friendly neighborhood HTML <template> tag might not have any exclusive attributes to brag about, it makes up by working harmoniously with others making it versatile and powerful tool in your web development arsenal!

How to Use HTML <template> Tag: Step by Step Guide

Let’s dive right into how we can use the HTML <template> tag. This handy little tool is a boon for web developers, making it possible to hold client-side content that you don’t want to render immediately when a page loads. It’s an effective way of storing markup chunks that can be cloned and inserted in the document via JavaScript.

Begin with the basics; create your <template> element within your HTML document. Here’s how it looks:

<template id="myTemplate">
  <h2>Title</h2>
  <p>Some text.</p>
</template>

It’s important to note that any script within a <template> won’t execute, images won’t load, audio files won’t play until the template is used.

The power of the <template> tag truly shines when paired with JavaScript. By using JavaScript, you can clone your template content and append it wherever needed in your document. For instance:

let temp = document.querySelector('#myTemplate');
let clone = temp.content.cloneNode(true);
document.body.appendChild(clone);

In this example, cloneNode(true) ensures all child nodes are also duplicated.

Remember! The <template> tag is most useful for templates containing large blocks of code or when the same block will be reused multiple times. But one common mistake I’ve seen among beginners is overusing this tag for small pieces of code or those not meant for reuse – this can lead to cluttered and hard-to-read code.

One more thing – remember that while support for <template> has grown considerably, not all browsers fully support it yet, especially older ones. Always check compatibility before implementing!

Real-World Examples of HTML <template> Tag Usage

Diving into some concrete examples, I’ll illustrate how the HTML <template> tag can be a real game-changer. Let’s say you’re building a photo gallery and want to create a pattern for displaying each photo. Instead of repeating the same block of HTML code for every single image, you can use the <template> tag to define this pattern once and then clone it as needed.

<template id="photo-template">
    <figure>
        <img src="" alt="">
        <figcaption></figcaption>
    </figure>
</template>

In your JavaScript code, you’d then grab this template, fill in the src and alt attributes for the <img> element and set the content of <figcaption>.

let template = document.getElementById('photo-template');
let clone = document.importNode(template.content, true);
clone.querySelector('img').src = 'path/to/photo.jpg';
clone.querySelector('img').alt = 'Description of photo';
clone.querySelector('figcaption').textContent = 'Caption for photo';

document.body.appendChild(clone);

Another common scenario would be creating a list where each item has similar structure but different data. Here’s an example:

<template id="list-item-template">
    <li><span class="data"></span></li>
</template>

<ul id="myList"></ul>

<script>
const data = ['First', 'Second', 'Third'];
const templateElement = document.getElementById('list-item-template');
const listElement = document.getElementById('myList');

data.forEach(item => {
    let cloneElement = document.importNode(templateElement.content, true);
    
    cloneElement.querySelector('.data').textContent = item;
    
    listElement.appendChild(cloneElement);
});
</script>

Avoiding common pitfalls is key when working with the HTML <template> tag. One mistake I often see is not using document.importNode when cloning the template’s content. If you simply use template.content.cloneNode(true), scripts within the template won’t be executed.

In conclusion, HTML <template> tag can be a powerful tool in your web development arsenal if used correctly. The examples above only scratch the surface of what’s possible with this flexible and efficient way to manage and manipulate chunks of DOM.

Conclusion: Recap on the HTML <template> Tag and Its Importance

The journey we’ve taken together through the world of HTML’s <template> tag has been enlightening, hasn’t it? We’ve explored its uses, attributes, and even dived into some practical examples. Let’s take a moment to recap what we’ve learned about this incredibly useful tool for web developers.

Firstly, remember that the <template> tag is an essential part of HTML5. It allows us to declare fragments of HTML that can be cloned and inserted in our document by JavaScript. Here’s a quick example:

<template id="myTemplate">
  <p>Hello, World!</p>
</template>

<script>
  let template = document.getElementById('myTemplate');
  let clone = template.content.cloneNode(true);
  document.body.appendChild(clone);
</script>

In this code snippet, you’ll notice that the content inside our <template> doesn’t show up on the webpage until we use JavaScript to clone it and append it to our body element.

Why is this important? Think efficiency! With the <template> tag, you’re not loading content until you need it which can significantly improve page load speeds. And as any seasoned developer knows – faster load times often mean happier users!

But like all tools in coding, there are common mistakes people tend to make with the <template> tag:

Remember these pitfalls and strive for clean, efficient code!

So there you have it – my thoughts on why mastering the HTML’s <template> tag is paramount for every budding web developer out there. It may seem like an innocuous detail amidst a sea of tags but trust me, once mastered; it’s a game-changer!

Cristian G. Guasch

Hey! I'm Cristian Gonzalez, I created HTML Easy to help you learn HTML easily and fast.

Related articles