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 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 Base64 Images in HTML (With Example) Images make up over 60% of a webpageâs total size, so optimizing how they load is essential. Instead of linking to external files, you can embed images directly in HTML using Base64 encoding. This technique is great for small visuals like icons or logos, helping reduce HTTP requests and improve perf
4 min read
How to convert image into base64 string using JavaScript ? In this article, we will convert an image into a base64 string using Javascript. The below approaches show the methods to convert an image into a base64 string using Javascript.ApproachHere we will create a gfg.js file which will include JavaScript code and one gfg.html file.Now we will put onchange
2 min read
How to Show Images on Click using HTML ? Display Images on Click Using HTML and JavaScript refers to techniques that dynamically show images when a user interacts with a webpage, such as clicking a button. This enhances user engagement by making web pages more interactive, using simple HTML, CSS, and JavaScript methods.Table of ContentChan
4 min read