Node.js With Express And EJS

Published Feb 26, 2015Last updated Apr 12, 2017

Why EJS

The beauty of EJS is that, you can create partial views using EJS . For example you can have a common header, footer, navigation for all pages and just change the internal content using EJS.
Also you are able to pass data to views. For instance consider the username, which is different for each user, using EJS you can do something like this:

app.get('/', function(req, res){ 
  res.render('index',{user:"John Smith"}) 
}); 

And set the dynamic username each time.

As the name implies, you can use javascript for generating HTML from EJS.

  • Create a Simple EJS Template

  • Create a views folder in your project

  • Create file -> index.ejs

<html>
  <head><title><%= title %></title></head>
  <body>
    welcome <%= user%>;
  </body>
</html>

Done! you have created your first template with EJS, You found <%= title %> in the above code. It is just a binding and we will discuss about that later. Now what you want to do is just render the index.ejs file from your node server using EJS view engine.

Rendering EJS

  • Create a server.js file, and install the ejs module.
  • Write code for your express app
var express = require('express'); 
var app = express();

Now, Inside you server.js set the view Engine to ejs as follows

app.set('view engine', 'ejs');

Create a route for your app

app.get('/', function(req, res){ 
 	res.render('index',{user: "Great User",title:"homepage"});
});

Remember our index.ejs file, we had put tags for binding title and user in the page, here in the render function we are passing the parameters for their values

Done! Run your server.js file

Creating Partial Views

So far we have created a single view using some dynamic data and rendered the output. Now we will try to create some Nested Views. i.e. Partial Views.

  • Replace contents of your index.ejs file with this:
<html>
  <head>
    <% include('header.ejs') %>
  </head>
  <body>
    <% include('body.ejs') %>
  </body>
</html>
  • Now create two more files in the views folder

header.ejs

<title>
Hello World
</title>

body.ejs

<div>
Welcome, Great User
</div>
  • Now start you server. You have embedded partial views into your main view for index.ejs.

Using JavaScript

As I said , you can use javascript for templating in ejs. Now we will see how it's done.

  • Write this in your index.ejs file,
<ul>
  <% users.forEach(function(user){ %>
    <%= user.name %>
  <% })%>
</ul>
  • Now Render the index.ejs file and pass an object array to the render function, like this
app.get('/', function(req, res){ 
  res.render('index',{users : [
            { name: 'John' },
            { name: 'Mike' },
            { name: 'Samantha' }
  ]});
});

That’s it, here we have iterated into the array, passed to the render object, and listed the names of each user using EJS.

Discover and read more posts from Naeem
get started
Enjoy this post?

Leave a like and comment for Naeem

2
2
2Replies
Pat
7 months ago

Respectfully, either this code has errors or lacks clarity. Please fix this so that it helps others instead of confusing them.

#1. For newcomers, its very helpful to display end results, github to your code, etc.
#2. You’re assuming the reader knows details that you’ve not mentioned.

It extremely frustrating for a person trying to learn a language and be faced with this kind of vague tutorial. The closest I’ve gotten to a result was this;

**EJS:**

<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”>
<script src=“https://ajax.googleapis.com…”></script>
<script src=“https://maxcdn.bootstrapcdn…”></script>
<link rel=“stylesheet” href="./style.css">
<% include(‘header.ejs’) %>
</head>
<body>
<ul>
<% users.forEach(function(user){ %>
<%= user.name %>
<% })%>
</ul>
</body>
</html>

**Javascript**
var express = require(‘express’);
var app = express();

//Now, Inside you server.js set the view Engine to ejs as follows
app.set(‘view engine’, ‘ejs’);
//Create a route for your app.
app.get(’/’, function(req, res) {
res.render(‘index’, {
users: [{ name: ‘John’ }, { name: ‘Mike’ }, { name: ‘Samantha’ }]
});
});

var server = require(‘http’).createServer(app);
server.listen(3000, function() {
console.log('Express is running on port…3000 ');
});

**RESULTS on Browser:**

John Mike Samantha

Younis Shah__
2 years ago

<ul>
<% users.forEach(function(user){ %>
<%= user.name %>
<% })%>
</ul>

app.get(’/’, function(req, res){
res.render(‘index’,[;
{ name: ‘John’ },;
{ name: ‘Mike’ },;
{ name: ‘Samantha’ };
]);
});

The above won’t render. It is missing “users” object in the .ejs file. It should have been like this:

app.get(’/’, function(req, res){
res.render(‘index’,{users : [;
{ name: ‘John’ },;
{ name: ‘Mike’ },;
{ name: ‘Samantha’ };
]});
});

Get curated posts in your inbox

Read more posts to become a better developer