Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Node.js Express Handlebars Tutorial to Show Static & Dynamic Images in Browser Using express-handlebars in Javascript

Posted on November 23, 2022

Welcome folks today in this blog post we will be showing the static and dynamic images in browser using handlebars library in node.js and express. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to initialize a new node.js project by using the below command as shown below

 

 

npm init -y

 

 

npm i express

 

 

npm i express-handlebars

 

 

As you can see we are installing the express library which will be the web server for this application and also express-handlebars library which will act as the view engine for the application.

 

 

Directory Structure of the App

 

 

Now guys just see the below directory structure of the node.js express app in handlebars view engine

 

 

 

 

Making the express app

 

 

Now guys we will be starting the express app at the port number 3000.

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
//importing modules
const express = require('express')
 
// 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}`));

 

 

As you can see in the above code we are importing the express library and then we are making the new express app. And after that we are setting the port number of the express app. And then we are using the listen() method of the express to start the app at the port number 3000.

 

 

Setting the Handlebars as View Engine

 

 

Now guys we will be setting the view engine of the express app as handlebars. For this first of all we will be importing the handlebars library and then we will be setting the view engine as shown below

 

 

JavaScript
1
2
3
4
const {engine} = require('express-handlebars')
 
app.engine('.hbs', engine({ extname: '.hbs',defaultLayout:false,layoutsDir:'views'}));
app.set("view engine", "hbs");

 

 

As you can see we are also disabling the defaultLayout and also we are providing the directory path where the views will be stored. For this we need to make the views directory

 

And also we need to make the public directory inside this application as the static directory. Here in this directory all the images will be stored which will be displayed in the application. You can use the express.static() method to do this as shown below

 

 

JavaScript
1
app.use(express.static('public'));

 

 

Now we need to make the get request of the /static route as shown below

 

 

1
2
3
4
// Route to display static src images
app.get("/static", (req, res) => {
    res.render("static");
});

 

 

As you can see that we are loading the static.hbs template which is stored inside the views directory

 

 

views/static.hbs

 

 

1
2
3
4
5
6
7
8
9
10
11
<!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/profile.jpg" alt="">
</body>
<html>

 

 

As you can see we are displaying the profile.jpg image which is stored inside the public directory. As we already made the public directory as static in express. Now if you open the browser and go to http://localhost:3000/static you will see the image rendered as shown below

 

 

 

 

Serving Dynamic Images in Handlebars

 

 

Now we will be writing another get request to the route /dynamic. And this time we will be providing the images dynamically by passing it to the handlebars template as shown below

 

 

JavaScript
1
2
3
4
5
6
7
8
// Route to display dynamic src images
app.get("/dynamic", (req, res) => {
    imageList = [];
    imageList.push({ src: "icons/facebook.webp", name: "facebook" });
    imageList.push({ src: "icons/linkedin.png", name: "linkedin" });
    imageList.push({ src: "icons/youtube.png", name: "youtube" })
    res.render("dynamic", { imageList: imageList });
});

 

 

As you can see that we have the imageList variable in which we are pushing the  images which are stored inside the icons folder and then we are using the render() method to render the handlebars template of dynamic.hbs and passing the images as data.

 

 

Displaying Dynamic Images in Handlebar Template

 

 

Now we need to make the dynamic.hbs file where we will be rendering the dynamic images passed to this handlebar template as shown below

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!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>

 

 

As you can see in the above handlebar template we are using the each loop to render all the images passed and display it using the img tag as shown above.

 

Now if you open the browser and go to http://localhost:3000/dynamic you will see the below images displayed

 

 

 

 

Wrapping the blog post this is the full source code of the index.js file as shown below

 

 

index.js

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//importing modules
const express = require('express')
const {engine} = require('express-handlebars')
 
// Express server's instance
const app = express();
 
app.engine('.hbs', engine({ extname: '.hbs',defaultLayout:false,layoutsDir:'views'}));
app.set("view engine", "hbs");
app.use(express.static('public'));
 
 
// 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/facebook.webp", name: "facebook" });
    imageList.push({ src: "icons/linkedin.png", name: "linkedin" });
    imageList.push({ src: "icons/youtube.png", name: "youtube" })
    res.render("dynamic", { imageList: imageList });
});
 
const PORT = process.env.PORT || 3000;
 
// listening
app.listen(PORT, () => console.log(`Server started running on PORT ${PORT}`));

Recent Posts

  • Android Java Project to Capture Image From Camera & Save it inside Gallery
  • Android Java Project to Crop,Scale & Rotate Images Selected From Gallery and Save it inside SD Card
  • Android Kotlin Project to Load Image From URL into ImageView Widget
  • Android Java Project to Make HTTP Call to JSONPlaceholder API and Display Data in RecyclerView Using GSON & Volley Library
  • Android Java Project to Download Youtube Video Thumbnail From URL & Save it inside SD Card
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme