How to Display Images using Handlebars in Node.js ?
Last Updated :
08 Jan, 2025
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
Approach
To display images using Handlebars in Node.js, pass the image URLs to the template from your server. In the Handlebars template, use the img tag with the passed URL to render the images dynamically.
Displaying images using Handlebars in Node.js allows you to build dynamic web pages.
Steps to Display Images using Handlebars
Step 1: Initialize Node project
npm init
Step 2: Install express and express-handlebars
npm install --save express express-handlebars
The Updated Dependencies in the package.json file
"dependencies": {
"express": "^4.19.2",
"express-handlebars": "^7.1.2",
}
Step 3: Setting up express server:
JavaScript
//importing modules
import express from "express"
import path from "path"
import exphbs from "express-handlebars"
// Express server's instance
const app = express();
const PORT = process.env.PORT || 3000;
// listening
app.listen(PORT, () => console.log(`Server started running on PORT ${PORT}`));
Project Structure:
project structureStep 3: Change the default view engine to handlebars: To serve static files like images from a directory named "images"
app.engine("handlebars", exphbs({ defaultLayout: "main" }));
app.set("view engine", "handlebars");
app.use(express.static("images"));
With the above line we are telling our Node.js app where our images will be stored. We will not have to specify a messy path to our image in our <img> tag.
Step 4: Define routes and render views accordingly
Node
// Route to display static src images
app.get("/static", (req, res) => {
res.render("static");
});
// Route to display dynamic src images
app.get("/dynamic", (req, res) => {
imageList = [];
imageList.push({ src: "icons/flask.png", name: "flask" });
imageList.push({ src: "icons/javascript.png", name: "javascript" });
imageList.push({ src: "icons/react.png", name: "react" });
res.render("dynamic", { imageList: imageList });
});
Handlebar templates: Now let us create a static.handlebars file in our views directory with the following content:
HTML
<!-- Filename - index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Handlebars Images Demo</title>
</head>
<body>
<h1>Display Static Images Using Handlebars In NodeJS</h1>
<br>
<img src="images/gfg.png" alt="" style="border: 5px inset black;">
</body>
<html>
Node
// Filename - index.js
//importing modules
import express from "express"
import path from "path"
import exphbs from "express-handlebars"
// Express server's instance
const app = express();
const PORT = process.env.PORT || 3000;
app.engine("handlebars", exphbs({ defaultLayout: "main" }));
app.set("view engine", "handlebars");
app.use(express.static("images"));
// Route to display static src images
app.get("/static", (req, res) => {
res.render("static");
});
// Route to display dynamic src images
app.get("/dynamic", (req, res) => {
imageList = [];
imageList.push({ src: "icons/flask.png", name: "flask" });
imageList.push({ src: "icons/javascript.png", name: "javascript" });
imageList.push({ src: "icons/react.png", name: "react" });
res.render("dynamic", { imageList: imageList });
})
// Listening
app.listen(PORT, () => console.log(`Server started running on PORT ${PORT}`));
node index.js
Output: Now, go to localhost:3000/static which will render GFG logo on the webpage.
Static img src displayNow let us create a dynamic.handlebars file in our views directory with the following content:
HTML
<!--index.html --><!DOCTYPE html>
<html lang="en">
<head>
<title>Handlebars Images Demo</title>
</head>
<body>
<h1>Display Dynamic Images Using Handlebars In NodeJS</h1> <br>
<div class="row">
{{#each imageList}}
<div class="col-md-4">
<div class="text-success" style="font-size: large;
font-weight: 700;">{{this.name}}</div>
<img src="{{this.src}}">
</div>
{{/each}}
</div>
</body>
<html>
Output: Now, go to localhost:3000/dynamic which will render some icons on the webpage. (The urls of these images are passed from server side).
Dynamic img src display
Similar Reads
How to display Image in Postman using Express ?
Postman is a powerful tool for testing APIs, but when it comes to displaying images, it can be a little bit tricky. This article, the process of setting up an Express server to serve images and accessing them using Postman.Prerequisites:PostmanExpress JSSteps to display Image in Postman:Step 1: Imag
2 min read
How to display text on hover over image using Tailwind CSS in React.js ?
In this article, we'll see how the text appears on hover over an image using tailwind CSS in a ReactJS app. With the help of Tailwind CSS utility classes, we can display the text or image or anything after hovering over an element in Reactjs. Prerequisites:NPM & Node.jsReact JSTailwindCSSApproac
4 min read
How to Send an Image using Ajax ?
Ajax stands for Asynchronous Javascript and XML and is used to make indirect requests to other origins. It can help you to perform a change to the web page dynamically.We can make an AJAX request with a special object called XMLHttpRequest which provides us with different methods to create an HTTP r
5 min read
How to Setup Handlebars View Engine in Node.js ?
Handlebars is a template engine that is widely used and easy to use. The pages contain .hbs extension and there are many other template engines in the market like EJS, Mustache, etc. Installation of hbs module: You can visit the link Install hbs module. You can install this package by using this com
2 min read
How to Add a Background Image in Next.js?
Next.js is a powerful React framework that allows for server-side rendering and the generation of static websites. Adding a background image to your Next.js application can enhance the visual appeal of your web pages. This article will guide you through the process of adding a background image to a
3 min read
How to Display Images in JavaScript ?
To display images in JavaScript, we have different approaches. In this article, we are going to learn how to display images in JavaScript. Below are the approaches to display images in JavaScript: Table of Content Using CreateElementUsing InnerHTMLApproach 1: Using CreateElementIn an HTML document,
2 min read
How to upload an image using HTML and JavaScript in firebase ?
Firebase is a product of Google which helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. No programming is required on the firebase side which makes it easy to use its features more efficiently. It provides cloud st
3 min read
How to add Image Carousel in Next.js ?
In this article, we are going to learn how we can add an Image Carousel in NextJS. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac.ApproachTo create image carousel in next.js we are going to use a react-re
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 display a PDF as an image in React app using URL?
If we use the fetch method then it will open a new window for displaying the PDF file and let users download the PDF. But if you don't want that then there is a way to do so. You can use the package called react-pdf, by using this package you can render the PDF in your React app by using the PDF URL
3 min read