Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • HTML Tutorial
  • HTML Exercises
  • HTML Tags
  • HTML Attributes
  • Global Attributes
  • Event Attributes
  • HTML Interview Questions
  • HTML DOM
  • DOM Audio/Video
  • HTML 5
  • HTML Examples
  • Color Picker
  • A to Z Guide
  • HTML Formatter
Open In App
Next Article:
Dynamic User Interfaces in JavaScript
Next article icon

Dynamic HTML Using Handlebars JavaScript

Last Updated : 13 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The Dynamic HTML Using Handlebars JavaScript consists of creating the user interactive web pages by combining the HTML with the Handlebars templating engine. The Handlebars mainly ease the process of dynamically rendering the HTML content by allowing the insertion of variables, expressions, and logic directly in the markup.

In this article, we will explore the process of rendering Dynamic HTML Using Handlebars JavaScript using practical examples.

Dynamic HTML Using Handlebars JavaScriptSyntax for Dynamic HTML Using Handlebars JavaScript

<script id="template" type="text/x-handlebars-template">
{{#each data}}
<!-- HTML structure using Handlebars expressions {{}} -->
{{/each}}
</script>

Approach to Render Dynamic HTML Using Handlebars JavaScript:

  • Firstly, add the CDN Link of the Handlebars Templating Engine.
  • Define the Handlebars template in the HTML file and then compiler and update the task list using the Handlebars.
  • The template is then compiled using Handlebars.compile() and a set of tasks is maintained in JavaScript.
  • There are functions to handle dynamic updates to the task list which shows the usage of Handlebars for creating data-driver HTML content.
  • The template is rendered with updated data upon user interactions like adding, removing, or toggling tasks.

Steps to Render Dynamic HTML Using Handlebars JavaScript

Step 1: Firstly, we will make the folder named root by using the below command in the VScode Terminal. After creation use the cd command to navigate to the newly created folder.

mkdir root
cd root

Step 2: Now create the below Project Structure in your project, including app.js and index.html.

Folder Structure:

--root
--index.html
--script.js

Example: We need to write the code for the script.js file, and code for index.html to render Dynamic HTML Using Handlebars JavaScript.

HTML
<!DOCTYPE html> <html> <head>     <title>         Dynamic HTML Using Handlebars JavaScript     </title>     <style>         body {             font-family: 'Arial', sans-serif;             margin: 20px;         }          h1 {             color: green;         }          #taskInput {             margin-bottom: 10px;         }          ul {             list-style-type: none;             padding: 0;         }          li {             margin-bottom: 5px;         }          li span {             margin-right: 10px;         }          button {             cursor: pointer;         }     </style> </head>  <body>     <h1>GeeksforGeeks</h1>     <h3>Dynamic HTML Using Handlebars JavaScript</h3>     <input type="text" id="taskInput" placeholder="Add a new task">     <button onclick="addTaskFn()">Add Task</button>     <ul id="taskList"></ul>     <script src= "https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js">     </script>     <script id="template" type="text/x-handlebars-template">         {{#each tasks}}             <li>                 <input type="checkbox" {{#if completed}}checked{{/if}}                      onclick="toggTaskFn('{{id}}')">                 <span>                     {{title}}                 </span>                 <button onclick="removeTaskFn('{{id}}')">                     Remove                 </button>             </li>         {{/each}}     </script>     <script src="script.js"></script> </body>  </html> 
JavaScript
let tasks = [     {         id: "1",         title: "Python",         completed: false     },     {         id: "2",         title: "ReactJS",         completed: true     }, ]; const src =     document.getElementById("template").innerHTML; const template = Handlebars.compile(src); function updateTaskList() {     const html = template({ tasks });     document         .getElementById("taskList").innerHTML = html; } function addTaskFn() {     const newTaskTitle =         document.getElementById("taskInput").value;     const newTask =     {         id: Date.now().toString(),         title: newTaskTitle,         completed: false     };     tasks.push(newTask);     updateTaskList();     document.getElementById("taskInput").value = ""; } function removeTaskFn(taskId) {     tasks =         tasks.filter(             task =>                 task.id !== taskId         );     updateTaskList(); } function toggTaskFn(taskId) {     tasks = tasks.map(task => {         if (task.id === taskId) {             task.completed = !task.completed;         }         return task;     });     updateTaskList(); } updateTaskList(); 

Output:

Output



Next Article
Dynamic User Interfaces in JavaScript

G

gauravgandal
Improve
Article Tags :
  • Web Technologies
  • HTML
  • View Engine

Similar Reads

  • How to add HTML elements dynamically using JavaScript ?
    We learn how to add HTML elements dynamically using JavaScript. A basic understanding of HTML, CSS, and JavaScript is required. Here we are going to use a button and by clicking this button, we can add an HTML element dynamically in this example. Below are the approaches used to add HTML elements dy
    2 min read
  • Dynamic User Interfaces in JavaScript
    User interfaces (UIs) have evolved from static layouts to dynamic and interactive experiences and JavaScript is a versatile and powerful programming language that plays a significant role in creating dynamic UIs that respond to user actions in real-time. Below are the methods to create a dynamic use
    2 min read
  • Design a Stock Market Dashboard using HTML CSS & JavaScript
    We will walk through the step-by-step process of designing a Stock Market Dashboard template using HTML, CSS, and JavaScript. This application will provide users with a dashboard interface where they can view a watchlist of stocks, search for specific stocks, and see detailed information about each
    11 min read
  • Create a Bookmark Landing Page using HTML CSS and JavaScript
    In this article, we are going to implement a Bookmark Landing Page using HTML, CSS, and JavaScript. Users can effortlessly add, manage, and remove bookmarks, resulting in a tidy digital library for their favorite websites. Bookmarking the Landing Page refers to a web page or website where the users
    5 min read
  • JavaScript HTML DOM
    The JavaScript HTML DOM (Document Object Model) is a powerful tool that represents the structure of an HTML document as a tree of objects. It allows JavaScript to interact with the structure and content of a webpage. By manipulating the DOM, you can update the content, structure, and styling of a pa
    4 min read
  • Dynamically Execute JavaScript in ElectronJS
    ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.I
    7 min read
  • JavaScript | JSON HTML
    HTML table: In the HTML, tables are defined by <table> tag, table's header are defined by <th> tag and by default table's header are placed in center and it is bold and row of the table is defined by <tr> and the data or information of the row is defined by <td> tag. Below co
    3 min read
  • How to Display Images using Handlebars in Node.js ?
    In this article, we will discuss how to display images using handlebars in Node.js. You may refer to this article for setting up handlebars View Engine in Node.js ApproachTo display images using Handlebars in Node.js, pass the image URLs to the template from your server. In the Handlebars template,
    3 min read
  • DHTML JavaScript
    DHTML stands for Dynamic HTML. Dynamic means that the content of the web page can be customized or changed according to user inputs i.e. a page that is interactive with the user. In earlier times, HTML was used to create a static page. It only defined the structure of the content that was displayed
    3 min read
  • How to Append Header to a HTML Table in JavaScript ?
    JavaScript allows us to dynamically modify the structure of a table based on user interaction or other dynamic events. Here we will use JavaScript to dynamically create a Header row and then append it to the HTML table. ApproachIn this approach, we are using create elements along with DOM manipulati
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences