DEV Community

Vijay Kumar
Vijay Kumar

Posted on

Handlebars

What is Handlebars ?

Handlebars is a simple templating language.
It uses a template and an input object to generate HTML or other text formats. Handlebars templates look like regular text with embedded Handlebars expressions.

This 👇 is a template,{{first.name}} is an expression or placeholder, where we pass dynamic data with the help of handlebars.

<p>{{first.name}} {{last.name}}</p>
Enter fullscreen mode Exit fullscreen mode

A handlebars expression is a {{, some contents, followed by a }}. When the template is executed, these expressions are replaced with values from an input object.

What is need of Handlebars 🤔?

1.Handlebars allows us to insert dynamic data into HTML templates.
2.This is particularly useful when generating content based on data from an API or user input
3.By using Handlebars templates, you can focus on the structure and layout of your HTML while keeping the data separate. This makes your code more modular and easier to maintain.
4.Handlebars can be integrated with various JavaScript frameworks and libraries, including Express.js for server-side rendering and client-side frameworks like Ember.js. This makes it a versatile choice for different parts of your tech stack.

Setting up Handlebars?

1.Client-Side Setup

  1. Include Handlebars via CDN For client-side use, you can include Handlebars directly in your HTML file using a CDN.
<!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/handlebars@latest/dist/handlebars.js"></script>
</head>
<body>
  <!-- Handlebars Template -->
  <script id="template" type="text/x-handlebars-template">
    <h1>{{title}}</h1>
    <p>{{description}}</p>
  </script>

  <!-- Where the rendered content will be injected -->
  <div id="content"></div>

  <script>
    // Fetch data and compile Handlebars template
    const data = {
      title: 'Hello World',
      description: 'This is a dynamic description.'
    };

    // Get the Handlebars template
    const source = document.getElementById('template').innerHTML;

    // Compile the template
    const template = Handlebars.compile(source);

    // Generate HTML with the template and data
    const html = template(data);

    // Insert HTML into the page
    document.getElementById('content').innerHTML = html;
  </script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

2.Server-Side Setup with Node.js and Express

  1. Install Handlebars Install Handlebars and Express using npm:npm install express express-handlebars 2.Set Up Express with Handlebars Create a basic Express server that uses Handlebars as the templating engine.
const express = require('express');
const exphbs = require('express-handlebars');
const path = require('path');

const app = express();

// Set up Handlebars as the view engine
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');

// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));

// Define a route
app.get('/', (req, res) => {
  res.render('home', {
    title: 'Hello World',
    description: 'This is a dynamic description.'
  });
});

// Start the server
const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

Enter fullscreen mode Exit fullscreen mode

Compiling Templates

1.1. Include Handlebars Library
Add the Handlebars library to your HTML via a CDN or local file:
<script src="https://cdn.jsdelivr.net/npm/handlebars@latest/dist/handlebars.js"></script>

  1. Define the Template Include your Handlebars template in your HTML file within a tag with a type attribute of text/x-handlebars-template. <code>&lt;script id=&quot;template&quot; type=&quot;text/x-handlebars-template&quot;&gt; &lt;h1&gt;{{title}}&lt;/h1&gt; &lt;p&gt;{{description}}&lt;/p&gt; &lt;/script&gt; </code></li> <li>Compile the Template In your JavaScript, get the template source, compile it into a function, and then use it to generate HTML. `// Step 1: Get the template source const source = document.getElementById(&#39;template&#39;).innerHTML;</li> </ol> <p>// Step 2: Compile the template<br> const template = Handlebars.compile(source);</p> <p>// Step 3: Define the data<br> const data = {<br> title: &#39;Hello World&#39;,<br> description: &#39;This is a dynamic description.&#39;<br> };</p> <p>// Step 4: Generate HTML<br> const html = template(data);</p> <p>// Step 5: Insert the HTML into the page<br> document.getElementById(&#39;content&#39;).innerHTML = html;<br> `</p> <h2> <a name="summary" href="#summary" class="anchor"> </a> Summary </h2> <p><strong>Handlebars Summary:</strong></p> <ol> <li><strong>Define Template</strong>: Create a template using <code>{{}}</code> syntax.</li> <li><strong>Compile Template</strong>: Convert the template into a function.</li> <li><strong>Render HTML</strong>: Pass data to the compiled template to generate HTML.</li> </ol> <p><strong>Benefits</strong>: Separates HTML from data, supports reusable components, and simplifies dynamic content rendering.</p>

Top comments (0)