EJS in Node.js: A Guide to Embedded JavaScript Templates

The template engine in Node.js is used to inject data into the HTML. Data can be JS objects, JSON, or raw text. Template engine makes it super easy to create dynamic websites as we can dynamically insert data into HTML based on user behaviour.

Some of the best templating engine libraries available that we can use in Node.js projects are Pug, Handlebars, Jade, Mustache, Dust.js, etc. But the best among these is EJS.

Also Read: How to Build a Todo App with NodeJS (Express & EJS)

What is EJS?

EJS is the most popular template engine that allows us to generate HTML markup with pure JavaScript. Using it we can embed JavaScript code directly into HTML pages. This allows us to use JavaScript methods, conditional statements, loops, etc. inside HTML.

Example Use Case:

This can be very useful, for example, if/else can be used to determine which element to show and which to hide, such as hiding the login button and showing the logout if the user is already logged in.

Benefits of Using Templating Engines:

  • Enhances the productivity of a developer.
  • Improves the readability, usability and maintainability of the application.
  • Fastens the performance of the 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.

Using EJS as Template Engine in Node.js

To use EJS as a template engine in a Node.js project, we use Express which is best compatible with it.

1. Creating a New Node.js Project

Create a new folder -> navigate to it -> execute the below command:

npm init

NPM stands for Node Package Manager used to install different NodeJS packages. We have a separate tutorial on NodeJS NPM if you want to read it.

package.json content

Now, a package.json file will automatically created inside the project folder:

package.json file

This contains various information about the project including the modules installed.

Next, create an app.js where we will write Node.js code:

touch app.js
app.js file

Install express and ejs modules using NPM:

npm install express ejs
npm install command

2. Setting a Basic Express Server

Now that we have our packages installed, let us get started with setting up our Express server and integrating the EJS template engine with our front end.

app.js:

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

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.listen(3000, () => {
    console.log("App listening on port 3000");
})

Inside the ‘index.js’ file, we first imported the Express module and created its instance ‘app’ to call its methods. Then we imported the path module and set the path of the views folder so that it can be accessible globally as EJS looks for a ‘views’ folder to render custom templates. Then we set EJS as middleware for the view engine.

3. Creating an EJS Template

Create a ‘views‘ folder in the project’s main directory if you haven’t. Inside it, create a homepage.ejs file. This will be our template file and make sure that its extension is ‘.ejs’ and not ‘.html’ or ‘.htm’ otherwise your templates will fail to render.

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

app.get('/', (req, res) => {
    res.render('homepage', { message: 'Hello World' })
})

Here we have used the get() method to create a home route, represent “/” which is the application’s default home page, and then define the functionality to send a message variable with a string containing Hello World to the HTML file ‘homepage.ejs’.

Now let’s create a simple EJS template and try to render that message value on our home route.

homepage.ejs

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        <%=message%> Page
    </title>
</head>

<body>
    <h1><%=message%></h1>
</body>

</html>

Notice the title element and the H1 element have the EJS template engine code, accepting the message value. 

4. Running the Application

Execute the below command in the terminal for the execution of our code:

node app.js
node app.js output

Now, enter the below URL in the search bar of a browser to open the application:

http://localhost:3000/
final output

And that’s it. We have successfully implemented EJS and this is just one of its usages. EJS has much more to offer which is enough to create fully dynamic web applications.

Conclusion

EJS is a templating language that lets us implement JavaScript inside HTML. This function helps us to inject data directly from the server to the client side. Using it we can also create reusable HTML layouts, that we can directly call into any page to have the same page design.

Read More: Node vs React

Reference

https://ejs.co

Aditya Gupta
Aditya Gupta
Articles: 161