W02 Learning Activity: Template Element
Overview
Sometimes you will want to build content but not render that content until later. For example, you may want to build a list of items but not render them until the user clicks a button. The HTML <template> element allows you to do just that.
Prepare
The HTML <template>
element is not rendered by the browser until evoked by script. The
<template>
element is useful for repeated HTML markup containing records or other data
that is used repeatedly.
Here is an example HTML template element:
<template id="product-card">
<section class="card">
<h2></h2>
<p></p>
<p></p>
<img class="tn" src="" alt="" loading="lazy" width="100" height="200">
</section>
</template>
In the example above, the template element is used to create a product card. The template
contains a
section
element with a class
of "card" and includes an h2 element for the product name, two p
elements for the product
description and price, etc., and an img
element for the product image.
The template
element is not rendered until it is cloned and inserted into the DOM.
Here is an example of how to clone and insert the template into the DOM:
const template = document.getElementById("product-card");
const productList = document.getElementById("product-list");
products.forEach((product) => {
const clone = template.content.cloneNode(true);
const [title, desc, price, img] = clone.querySelectorAll("h2, p, p, img");
title.textContent = product.name;
desc.textContent = product.description;
price.textContent = product.price;
img.src = product.image;
img.alt = product.name;
productList.appendChild(clone);
});
In the example above, the template is cloned and the content is populated with data from the
products
array. The cloned template is then appended to a product-list
element. Note that the use of the
.cloneNode()
method and the selection of the elements of the template as const
variables.
Example on CodePen: Template Element
Optional Resources
- The Content Template Element – MDN
- HTML Template Tag – w3schools