JavaScript Template Element

JavaScript Template Element

JavaScript Template Element

The <template> element in HTML is a special tag that is used to define HTML fragments that are not rendered when the page loads. These fragments can be accessed and cloned later via JavaScript. The <template> tag is perfect for scenarios where you want to define a piece of reusable HTML that won't be immediately displayed but will be used later when needed.

In JavaScript, the <template> tag provides a way to store HTML content that can be accessed and manipulated dynamically. The contents of a <template> element are inert until they are cloned and inserted into the document.

Key Features of the <template> Element

  1. Inactive by Default: The contents of the <template> element are not rendered when the page loads. They are not part of the document's layout and do not affect performance.
  2. Reusable HTML Fragments: You can define reusable HTML snippets that can be cloned and inserted at any point in the document later using JavaScript.
  3. Supports Embedded Content: You can use the <template> tag to store complex HTML structures, including forms, divs, or even other templates.

Basic Syntax of the <template> Element

<template id="my-template"> <div class="template-content"> <h2>Template Heading</h2> <p>This is a template content.</p> </div> </template>

In this example:

  • The contents inside the <template> are not rendered when the page loads.
  • The template is given an id so it can be accessed and manipulated by JavaScript.

How to Use the <template> Element with JavaScript

You can access and manipulate the content of a template using JavaScript. The most common method is to use document.getElementById() to get the template, then clone its content using the content property.

Example 1: Cloning and Inserting Template Content

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Template Example</title> </head> <body> <h1>Using Template Element</h1> <!-- Define the template --> <template id="my-template"> <div class="content"> <h2>Template Heading</h2> <p>This content was added dynamically using the template element!</p> </div> </template> <!-- A button to trigger the insertion of the template content --> <button id="insert-template">Insert Template</button> <!-- The place where the content will be inserted --> <div id="container"></div> <script> // Get the template element by ID const template = document.getElementById('my-template'); // Get the container where the template content will be inserted const container = document.getElementById('container'); // Get the button and add an event listener to it document.getElementById('insert-template').addEventListener('click', function() { // Clone the template content const clone = document.importNode(template.content, true); // Append the cloned content to the container container.appendChild(clone); }); </script> </body> </html>

Explanation:

  1. <template id="my-template"> defines the HTML content, but it won't be rendered immediately.
  2. The template.content property gives access to the contents of the template.
  3. document.importNode(template.content, true) creates a copy of the template's content, including its DOM nodes and any child elements.
  4. The cloned content is then appended to a container element using container.appendChild(clone) when the button is clicked.

How Template Works

  • The content inside the <template> element is inert and not rendered when the page loads.
  • When you need the content, you can access it using the content property of the template.
  • After accessing the content, you clone it and insert it into the page.

Example 2: Using Template to Display Dynamic Content

In this example, the template can be used to dynamically display content that is dependent on some variables, such as user input or data from an API.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dynamic Template Example</title> </head> <body> <h1>Dynamic Template Example</h1> <!-- Define the template --> <template id="user-template"> <div class="user-card"> <h2></h2> <p></p> </div> </template> <div id="user-container"></div> <script> const users = [ { name: 'Alice', bio: 'Web Developer' }, { name: 'Bob', bio: 'Graphic Designer' }, { name: 'Charlie', bio: 'Data Scientist' } ]; // Get the template and the container const template = document.getElementById('user-template'); const container = document.getElementById('user-container'); // Iterate over the user data and insert a cloned template for each user users.forEach(user => { // Clone the template content const clone = document.importNode(template.content, true); // Set dynamic content clone.querySelector('h2').textContent = user.name; clone.querySelector('p').textContent = user.bio; // Append the cloned content to the container container.appendChild(clone); }); </script> </body> </html>

Explanation:

  • users array: This is the data you want to display.
  • The script clones the template and inserts dynamic content (the user's name and bio) into the shadow DOM before adding it to the page.
  • This allows for dynamic insertion of user data into the page.

Advantages of Using <template>

  1. Efficiency: You can define reusable HTML structures that are not rendered until needed. This can help improve performance, especially in large applications where content is conditionally added.
  2. Separation of Concerns: By using templates, you can keep the HTML structure separate from the logic that adds it to the DOM, making the code cleaner and easier to maintain.
  3. Encapsulation: Templates can hold complex DOM structures without immediately affecting the page’s rendering, which is especially useful in large, interactive web apps.

Template in Web Components

Templates are often used in Web Components to define the structure and styles of a custom element. Using <template> inside a custom element’s shadow DOM allows for clean separation of concerns, which leads to more modular and reusable components.

class MyElement extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); // Define the template const template = document.createElement('template'); template.innerHTML = ` <style> p { color: blue; } </style> <p>My Web Component with a Template!</p> `; // Attach template content to shadow DOM this.shadowRoot.appendChild(template.content.cloneNode(true)); } } customElements.define('my-element', MyElement);

Usage in HTML:

<my-element></my-element>

Summary

  • The <template> element allows you to define reusable HTML fragments that are not rendered immediately when the page loads.
  • You can access the template's content through JavaScript, clone it, and insert it dynamically into the document.
  • Templates are a great way to modularize your HTML and create reusable components, especially when combined with Web Components.
Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close