Skip to content

HTML Templates Populating Dynamic Data with JavaScript

  • by

HTML templates are a way of defining reusable HTML structures that can be populated with dynamic data at runtime. In JavaScript, HTML templates can be defined using a variety of techniques, including:

1. Template literals: With template literals, you can define an HTML template as a string and interpolate dynamic data into the template using ${} syntax.

const data = { title: "My Title", body: "Lorem ipsum dolor sit amet..." };
const template = `
  <article>
    <h1>${data.title}</h1>
    <p>${data.body}</p>
  </article>
`;

2. HTML templates: HTML templates are a native feature of HTML that allows you to define a template using the <template> element.

<template id="my-template">
  <article>
    <h1></h1>
    <p></p>
  </article>
</template>

HTML Templates Example

Simple example code using an HTML template to populate dynamic data:

<!DOCTYPE html>
<html>
  <head>
    <title>HTML Templates Example</title>
  </head>
  <body>
    <template id="my-template">
      <article>
        <h1></h1>
        <p></p>
      </article>
    </template>

    <div id="container"></div>

    <script>
      const data = [
        { title: "Article 1", body: "Lorem ipsum dolor sit amet..." },
        { title: "Article 2", body: "Consectetur adipiscing elit..." },
        { title: "Article 3", body: "Praesent vel nisi eget odio..." }
      ];
      
      const template = document.getElementById("my-template");

      data.forEach((item) => {
        const clone = template.content.cloneNode(true);
        clone.querySelector("h1").textContent = item.title;
        clone.querySelector("p").textContent = item.body;
        document.getElementById("container").appendChild(clone);
      });
    </script>
  </body>
</html>

Output:

HTML Templates Populating Dynamic Data with JavaScript

Comment if you have any doubts or suggestions on this HTML JS topic.

Note: The All HTML Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *