CodeGym /Courses /Frontend SELF EN /Template Tags

Template Tags

Frontend SELF EN
Level 10 , Lesson 5
Available

5.1 The <template> Tag

The <template> tag in HTML lets developers define HTML fragments that won't be shown when the page loads but can be used later with JavaScript. It's super handy for dynamically creating and inserting content like list elements, product cards, and other repeatable structures.

The <template> element is used to store HTML code that won't show up on the page right away. The stuff inside <template> doesn't get rendered by the browser when the page loads, but it's available through the DOM (Document Object Model) and can be cloned and inserted into the document using JavaScript.

Syntax:

HTML
    
      <template>
        <!-- Template content -->
      </template>
    
  

Main Features of the <template> Tag

  1. Hiding content: The content inside the <template> tag doesn't display on the page when it loads.
  2. JavaScript usage: You can clone and insert the content of a <template> tag into the DOM via JavaScript.
  3. Deferred loading: Lets you load and display content only as needed, which can boost page performance.

Example of using the <template> Tag

In this example, pressing the "Add Item" button creates a new list item that gets added to the <ul> list. The template for the new list item is defined inside the <template> tag.

HTML
    
      <button id="addButton">Add Item</button>
      <ul id="itemList"></ul>
      <template id="itemTemplate">
        <li class="item">This is a new item</li>
      </template>
    
  
JavaScript
    
// Getting references to DOM elements we'll use
const addButton = document.getElementById('addButton'); // "Add" button
const itemList = document.getElementById('itemList'); // List to which we'll add items
const itemTemplate = document.getElementById('itemTemplate'); // List item template

// Adding an event listener to the "Add" button
addButton.addEventListener('click', () => {
  // Clone the contents of the list item template
  const newItem = itemTemplate.content.cloneNode(true); // true means deep cloning (including all child elements)

  // Add new item to the list
  itemList.appendChild(newItem); 
});
    
  

5.2 Example: Generating Product Cards

You can use <template> and JavaScript to generate a list of items—like product cards, for instance.

Example of using the <template> Tag:

HTML
    
      <h1>Product List</h1>
      <div id="productList"></div>
      <template id="productTemplate">
        <div class="item">
          <h2 class="title"></h2>
          <p class="description"></p>
          <span class="price"></span>
        </div>
      </template>
    
  
JavaScript
    
// Waiting for the DOM to load completely before running the script
document.addEventListener('DOMContentLoaded', () => {
  // Array of product data
  const products = [
    { title: 'Product 1', description: 'Description of Product 1', price: '$100' },
    { title: 'Product 2', description: 'Description of Product 2', price: '$200' },
    { title: 'Product 3', description: 'Description of Product 3', price: '$300' },
  ];

  // Getting references to elements in the DOM
  const productList = document.getElementById('productList'); // Container for the product list
  const template = document.getElementById('productTemplate').content; // Product element template

  // Looping through the product array and creating a list element for each
  products.forEach(product => {
    // Clone the product template
    const clone = document.importNode(template, true); // true means deep clone

    // Fill in data in the cloned template
    clone.querySelector('.title').textContent = product.title;
    clone.querySelector('.description').textContent = product.description;
    clone.querySelector('.price').textContent = product.price;

    // Add the filled template to the product list
    productList.appendChild(clone);
  });
});
    
  

Explanation

  • <template> tag: Contains HTML code that isn't displayed when the page loads.
  • document.importNode(template, true) method: Clones the template content.
  • querySelector and textContent methods: Used to change the content of the cloned template before inserting it into the document.

5.3 Advantages of the <template> Tag

Performance Improvement

Using templates lets you pre-load HTML code you'll use later. This can boost page performance because template content isn't rendered and doesn't affect initial page load.

Simplifying Dynamic Content

Templates make creating dynamic content easier. Instead of building HTML code programmatically with JavaScript, you can just clone and tweak pre-made templates.

Convenience and Readability

Templates make code more readable and organized, as HTML code for repeatable elements can be stored separately, rather than being stuck into JavaScript.

Example with Conditional Content Display:

HTML
    
      <h1>Operation Results</h1>
      <div id="messageContainer"></div>

      <template id="messageTemplate">
        <div class="message">
          <p class="content"></p>
        </div>
      </template>
    
  
JavaScript
    
document.addEventListener('DOMContentLoaded', () => {
  // Getting references to elements in the DOM
  const messageContainer = document.getElementById('messageContainer'); // Container for messages
  const template = document.getElementById('messageTemplate').content; // Message template

  // Function to display a message
  function showMessage(type, text) {
    // Clone the message template
    const clone = document.importNode(template, true); // true means deep clone

    // Get reference to the message element inside the clone
    const messageDiv = clone.querySelector('.message');

    // Add a class corresponding to the message type (success or error)
    messageDiv.classList.add(type);

    // Set the message text
    messageDiv.querySelector('.content').textContent = text;

    // Add the message to the container
    messageContainer.appendChild(clone);
  }

  // Call the function to display messages
  showMessage('success', 'Operation completed successfully!');
  showMessage('error', 'An error occurred during the operation.');
});
    
  

Explanation:

  • showMessage() function: Takes the message type (success or error) and message text, clones the template, and adds it to the message container.
  • .success and .error classes: Applied to the cloned template depending on the message type for styling.
1
Task
Frontend SELF EN, level 10, lesson 5
Locked
List with