Step-by-Step Guide to Using EJS Template Engine in Nodejs in 2021

Ejs Template Engine In Nodejs Featured Image

In today’s tutorial, I am going to walk you through using the EJS template engine for your next awesome Nodejs project.

Throughout this guide, we will be using Express.js as our server framework.

Before we proceed any further, let us get our basics right.

What is a Templating Engine for Nodejs?

A template or templating engine for Nodejs refers to a system that injects data into the HTML template of your app from the client-side.

For a better understanding, take a look at this well-explained diagram – thanks to Tutorials Teacher for the same!

Ejs Template Engine In Nodejs Process
Template Engine Data Rendering Process

This diagram clearly explains how our Nodejs server is able to input data onto our HTML template with the use of a templating engine.

There are various templating engine libraries available for you to use on NPM:

  • EJS
  • Pug
  • Handlebars
  • Jade
  • Mustache
  • Nunjucks
  • Dust.js
  • Vash
  • haml
  • atpl

Now that we understand what are templating engines in Nodejs, let us now take a look at some benefits. Of course, you must have guessed a few, but let me throw some light on those you probably didn’t 😊.

Benefits of Using Templating Engines

Obviously, there are benefits involved in using templating engines as the reason why it is so widely used by developers. Below I have listed out quite a few:

  • Enhances the productivity of a developer.
  • Improves the readability, usability and maintainability of your application.
  • Fastens performance of your application.
  • Maximizes client-side data processing.
  • Makes it easy to reuse templates on multiple pages.
  • Enables accessibility of templates from CDNs also known as Content Delivery Networks.

Okay, so we’re done with understanding the basics of template engines.

What is EJS Template Engine in Nodejs?

Ejs Template Engine In Nodejs

EJS is again a templating language or engine that allows you to generate HTML markup with pure JavaScript. And this is what makes it perfect for Nodejs applications.

In simple words, the EJS template engine helps to easily embed JavaScript into your HTML template.

Getting Started with Using EJS Template Engine in Nodejs Project

To get started with using the EJS template engine in your Nodejs project, we must first install the package.

As a prerequisite to this tutorial mentioned earlier, we are using Express.js for our server.

1. Creating & Configuring Nodejs Project

Let us first create our Node project and get going from there.

$ npm init -y

Your package.json file should now be created and should look like this:

{
  "name": "6_EJS_NODEJS_APP",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Next, create your .js file

$ touch index.js

Let us now install all our dependencies/packages.

$ npm i express ejs

Now that we have our packages installed, let us set up our mini application’s backend.

Switch to your application’s .js file, here I have created index.js, hence I am working in that file.

Let us get started with setting up our Express server and integrating the EJS template engine with our frontend.

const express = require('express');
const app = express();
const path = require('path');

// Setting EJS as templating engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.listen(3000, () => {
    console.log("APP IS LISTENING ON PORT 3000!")
})

Now, as default behavior, the EJS template engine looks for a ‘views’ folder to render our HTML templates.

Up to this point, your index.js and file structure of your application must look like this.

Ejs Template Engine In Nodejs File Structure

These lines make sure that the ‘views’ folder is accessible globally:

const path = require('path');
app.set('views', path.join(__dirname, 'views'));

If you don’t get what the path module does, click here to read about it!

2. Creating EJS Templates

Let’s create a ‘views’ folder in our project’s main directory and inside it, let’s create our homepage’s template and name it as homepage.ejs. Make sure your template file extension names consist of ‘.ejs’ and not ‘.html’ or ‘.htm’ otherwise your templates will fail to render.

Let us now set up our home page route in index.js and pass a name-value in the form of an object (key-value pair):

app.get('/', (req, res) => {
    res.render('homepage', { name: 'Monroe' })
})

Go ahead and configure a simple HTML template and try and render that name value on our home route from the client-side via the EJS template engine. For the sake of simplicity, I am embedding my CSS code into my HTML template.

Here’s my homepage.ejs now looks:





   
   
   
   <br />         <%=name%>'s Sweets & Candy<br />    

   




   

Welcome to <%=name%>'s Sweets & Candy!


   

Lorem ipsum dolor sit amet consectetur adipisicing elit. Neque officia sint explicabo non labore sit eaque quasi
        deleniti ullam fugiat obcaecati blanditiis molestiae, praesentium dicta tempore laborum, similique, soluta
        aliquam.
        Dolores alias molestias quidem, culpa minima, repellendus sapiente suscipit, vero inventore error magnam quas
        provident debitis? Tenetur repellat blanditiis perferendis laborum. Hic a qui eum aperiam, voluptatibus sint!
        Dicta, totam?
        Laudantium explicabo natus dolore aspernatur laboriosam perspiciatis provident hic facilis accusamus delectus
        praesentium voluptates nobis quam, a, corrupti aliquid officiis. Eaque, corrupti nostrum repellat dolorum fuga
        enim voluptas molestias obcaecati!
        Beatae tempore quod esse distinctio ipsa commodi aperiam iure architecto, numquam illum delectus. Maxime cumque
        reprehenderit, nam ut eligendi voluptate a assumenda similique ea quae quibusdam reiciendis explicabo sequi in?
        Animi fuga aliquid enim repudiandae ratione optio inventore aspernatur eaque consectetur totam. Aut officia at
        accusamus, commodi iste nostrum molestias sed. Harum quis libero iusto ea quae nostrum fuga nobis!





Notice the title element and the H1 element consisting of EJS template engine code, accepting the ‘name’ value. You can try your hands on and change the name value from the index.js file and watch the name change!

Here’s what my ugly home page looks like:

Ejs Template Engine In Nodejs Ugly Home

Conclusion

This tutorial explained what are templating engines, some of their benefits and briefed you about the EJS template engine in Nodejs.

Stay tuned for more exciting entry-level to intermediate Nodejs tutorial posts like this!

Noteworthy References

Using EJS Template Engine in Nodejs – GeeksforGeeks

Template Engine in Nodejs – Tutorials Teacher

EJS Template Engine Official Website