Node.js With Express And EJS

Published Feb 26, 2015Last updated Apr 12, 2017


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

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

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:
    <% include('header.ejs') %>
    <% include('body.ejs') %>
  • Now create two more files in the views folder


Hello World


Welcome, Great User
  • 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,
  <% users.forEach(function(user){ %>
    <%= %>
  <% })%>
  • 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