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:
How to use ReactJS with HTML Template ?
Next article icon

How to use Handlebars to Render HTML Templates ?

Last Updated : 06 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Handlebars is a powerful template engine that allows us to create dynamic HTML templates. It helps to render HTML templates easily. One of the advantages of Handlebars is its simplicity, flexibility, and compatibility with various web development frameworks.

These are the following methods:

Table of Content

  • Using npm package
  • Using CDN Link

Using npm package

Steps to use Handlebars to render HTML templates

Step 1: Create a new server using the following command.

npm init -y

Step 2: Install the necessary package in your application using the following command.

npm install express 
npm install hbs

Step 3 : For using a Handlebars in the Express.js code you must create a folder name "views" and in there create a file which must be end with ".hbs". Otherwise you got error.

Example: abc.hbs

Folder Structure:

Screenshot-_284_
Folder structure

The updated dependencies in package.json file will look like:

 "dependencies": {
"express": "^4.18.3",
"hbs": "^4.2.0"
}
}

Example: Write the following code in the files created as shown in folder structure

HTML
{{!-- template.hbs code... --}}  <html>  <head>     <title>{{ title }}</title>     <style>         body {             font-family: 'Segoe UI', Tahoma,                  Geneva, Verdana, sans-serif;             background-color: #f8f9fa;             margin: 0;             padding: 0;             height: 100vh;             color: #444;             line-height: 1.6;         }          .container {             display: flex;             justify-content: space-between;             max-width: 900px;             padding: 20px;             width: 55vw;         }          .card {             flex: 0 0 calc(33.33% - 20px);             background-color: #58e724;             margin-bottom: 20px;             padding: 20px;             border-radius: 10px;             box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);             transition: transform 0.3s ease;             margin-left: 9rem;         }          .card:hover {             transform: translateY(-5px);         }          h2 {             color: #fff;             margin-bottom: 10px;             text-align: center;         }          p {             color: #666;             text-align: center;         }          .author {             font-style: italic;             color: #888;         }          .button {             display: block;             width: 100%;             margin-top: 20px;             padding: 5px;             text-align: center;             color: #fff;             background-color: #007bff;             border: none;             border-radius: 5px;             cursor: pointer;             transition: background-color 0.3s ease;             text-decoration: none;         }          .button:hover {             background-color: #0056b3;         }          .main_heading {             text-align: center;             margin-top: 5rem;             margin-bottom: 20px;             color: rgb(27, 230, 91);         }     </style> </head>  <body>     <h1 class="main_heading">         This is a Example to use Handlebars          to render HTML templates     </h1>     <div class="container">         {{#each books}}         <div class="card">             <h2>{{ this.title }}</h2>             <p class="author">                 Written by: {{ this.author }}             </p>             <div class="body">                 {{{ this.synopsis }}}             </div>             <a href="#" class="button">                 Read More...             </a>         </div>         {{/each}}     </div> </body>  </html> 
JavaScript
// server.js code....  const express = require('express'); const app = express(); const PORT = process.env.PORT || 3000;  app.set('view engine', 'hbs');  const data = {     title: 'Handlebars Example',     books: [         {             title: 'Book 1',             author: 'John Doe',             synopsis: 'This is the synopsis of book 1.'         },         {             title: 'Book 2',             author: 'Jane Smith',             synopsis: 'This is the synopsis of book 2.'         },         {             title: 'Book 3',             author: 'Bob Johnson',             synopsis: 'This is the synopsis of book 3.'         }     ] };  // Define a route to render a template app.get('/', (req, res) => {     res.render('template', data); });  app.listen(PORT, (err) => {     if (err) {         console.log(err);     } else {         console.log(`Server is running on port ${PORT}`);     } }); 

To run the code wite in the command prompt

node server.js

And open a new tab of your browser and type the following command to show the output

http://localhost:3000/

Output:

Handlebars
Output

Using CDN Link

  • First create a Html template and include the Handlebars CDN link in the <head> section using <script> tag.
  • Then create a JavaScript section at the bottom of the HTML file or in an external JavaScript file and in the javascript code define the data object containing information about the books. .
  • For compile the Handlebars template and retrieving its content using document.getElementById('book-template').innerHTML and then used Handlebars.compile() method.

Example: The below code uses the handlebars CDN Link to use use handlebars.

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport" content= "width=device-width, initial-scale=1.0">     <title>Handlebars Example</title>     <script src= "https://cdn.jsdelivr.net/npm/[email protected]/dist/handlebars.min.js">     </script>     <style>         body {             font-family:                  'Segoe UI', Tahoma, Geneva,                  Verdana, sans-serif;             background-color: #f8f9fa;             margin: 0;             padding: 0;             height: 100vh;             color: #444;             line-height: 1.6;         }          .container {             display: flex;             justify-content: space-between;             max-width: 900px;             padding: 20px;             width: 55vw;         }          .card {             flex: 0 0 calc(33.33% - 20px);             background-color: #58e724;             margin-bottom: 20px;             padding: 20px;             border-radius: 10px;             box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);             transition: transform 0.3s ease;             margin-left: 9rem;         }          .card:hover {             transform: translateY(-5px);         }          h2 {             color: #fff;             margin-bottom: 10px;             text-align: center;         }          p {             color: #666;             text-align: center;         }          .author {             font-style: italic;             color: #888;         }          .button {             display: block;             width: 100%;             margin-top: 20px;             padding: 5px;             text-align: center;             color: #fff;             background-color: #007bff;             border: none;             border-radius: 5px;             cursor: pointer;             transition: background-color 0.3s ease;             text-decoration: none;         }          .button:hover {             background-color: #0056b3;         }          .main_heading {             text-align: center;             margin-top: 5rem;             margin-bottom: 20px;             color: rgb(27, 230, 91);         }     </style> </head>  <body>     <h1 class="main_heading">         This is an Example to use Handlebars to          render HTML templates     </h1>     <div class="container"></div>      <script id="book-template"          type="text/x-handlebars-template">         {{#each books}}         <div class="card">             <h2>{{ this.title }}</h2>             <p class="author">Written by: {{ this.author }}</p>             <div class="body">{{{ this.synopsis }}}</div>             <a href="#" class="button">Read More...</a>         </div>         {{/each}}     </script>      <script>         const data = {             title: 'Handlebars Example',             books: [                 {                     title: 'Book 1',                     author: 'John Doe',                     synopsis:                          'This is the synopsis of book 1.'                 },                 {                     title: 'Book 2',                     author: 'Jane Smith',                     synopsis:                          'This is the synopsis of book 2.'                 },                 {                     title: 'Book 3',                     author: 'Bob Johnson',                     synopsis:                          'This is the synopsis of book 3.'                 }             ]         };         const source = document.             getElementById('book-template').innerHTML;         const template = Handlebars.compile(source);         const html = template(data);         document.querySelector('.container').             innerHTML = html;     </script> </body>  </html> 

Output:

Screenshot-_282_
Output

Next Article
How to use ReactJS with HTML Template ?
author
skaftafh
Improve
Article Tags :
  • Web Technologies
  • HTML
  • EJS-Templating Language

Similar Reads

  • How to reuse template HTML block in Angular ?
    Code Reusability is the capacity to repurpose pre-existing code when developing new software applications. It will allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it. In this article, we will learn How to reuse template HTM
    2 min read
  • How to use ReactJS with HTML Template ?
    We all know ReactJS is a front-end development framework. For the front end, we need to create HTML templates. So, this article teaches you how to use HTML templates in ReactJS. The process is very simple.  Prerequisites:NodeJS or NPMReact JSApproach: We will create a simple one-page HTML template i
    4 min read
  • How to Pass/Access Node.js Variable to an HTML file/template ?
    When building web applications with Node.js, it’s often necessary to pass server-side variables to the client-side for rendering dynamic content. This can be achieved using various techniques and templating engines. This article will guide you through different methods to pass and access Node.js var
    2 min read
  • How to separate Handlebars HTML into multiple files / sections using Node.js ?
    In this article, we will learn about separating Handlebars HTML into multiple files/sections using Node.js and using it on any page that you want. It helps in reducing the repetition of code. For example, instead of adding the whole navbar on each page, you can just make a template of that navbar an
    3 min read
  • How to use Template Engines in Express JS ?
    Express.js is a popular web framework for Node.js that simplifies the process of building web applications. One of the key features of Express is its ability to integrate with template engines, allowing developers to dynamically generate HTML pages with data from their server. In this article, we'll
    2 min read
  • How to Install & Use EJS Template Engine ?
    EJS (Embedded JavaScript) is mainly a templating language for JS which allows dynamic content generation in web-based applications. This EJS Template allows us to embed the JS code directly in the HTML markup, which enables the integration of data and logic into the presentation layer. We can use EJ
    3 min read
  • How to include a template with parameters in EJS ?
    EJS (Embedded JavaScript) is a templating language that enables dynamic content generation in HTML files using JavaScript syntax. EJS templates consist of HTML code mixed with JavaScript expressions enclosed within <% %> tags. We will discuss the following approaches to include template with p
    4 min read
  • How to include a template with parameters in EJS?
    In EJS, we can include templates with parameters for the reuse of modular components in web applications. By passing parameters during the inclusion, we can create interactive templates. In this article, we will see a practical example of including a template with parameters in EJS. Below is the syn
    4 min read
  • How To Convert From .ejs Template to React?
    Converting from Embedded JavaScript templates (.ejs) to React can significantly enhance the flexibility and interactivity of your web applications. React’s component-based architecture provides a more dynamic way to build user interfaces compared to traditional templating engines like EJS. This arti
    4 min read
  • Angular PrimeNG Form TreeSelect Templates
    Angular PrimeNG is an open-source library that consists of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will be seeing the Angular PrimeNG Form TreeSelect Component. The TreeSelect Compone
    4 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