Use EJS to Template Your Node Application

Free Course

Build Your First Node.js Website

Node is a powerful tool to get JavaScript on the server. Use Node to build a great website.

When creating quick on-the-fly Node applications, an easy and fast way to template our application is sometimes necessary. So far we’ve been building out full MEAN applications and Angular acts as our templating engine.

For applications that need quick templating, there are many options that we can use.

Jade comes as the view engine for Express by default but that syntax just flat out scares me. EJS is one alternative does that job well and is very easy to set up. Let’s take a look at how we can create a simple application and use EJS to include repeatable parts of our site (partials) and pass data to our views.

Our Test Application

We will be making two pages for our application with one page with

full width and the other with a sidebar.

File Structure

Here are the files we’ll need for our application. We’ll do our templating inside of the views folder and the rest is pretty standard Node practices.

- views
----- partials
---------- footer.ejs
---------- head.ejs
---------- header.ejs
----- pages
---------- index.ejs
---------- about.ejs
- package.json
- server.js

package.json will hold our Node application information and the dependencies we need (express and EJS). server.js will hold our Express server setup, configuration. We’ll define our routes to our pages here.

Node Setup

Let’s go into our

package.json file and set up our project there.

{
  "name": "node-ejs",
  "main": "server.js",
  "dependencies": {
    "ejs": "^1.0.0",
    "express": "^4.6.1"
  }
}

All we will need is Express and EJS. Now we have to install the dependencies we just defined. Go ahead and run:

$ npm install

With all of our things installed, let’s configure our application to use EJS and set up our routes for the two pages we need: the index page (full width) and the about page (sidebar). We will do all of this inside our

server.js file.

// server.js
// load the things we need
var express = require('express');
var app = express();

// set the view engine to ejs
app.set('view engine', 'ejs');

// use res.render to load up an ejs view file

// index page 
app.get('/', function(req, res) {
    res.render('pages/index');
});

// about page 
app.get('/about', function(req, res) {
    res.render('pages/about');
});

app.listen(8080);
console.log('8080 is the magic port');

Here we define our application and set it to show on port 8080. We also have to set EJS as the view engine for our Express application using

app.set('view engine', 'ejs');. Notice how we send a view to the user by using res.render(). It is important to note that res.render() will look in a views folder for the view. So we only have to define pages/index since the full path is views/pages/index.

Start Up our Server

Go ahead and start the server using:

$ node server.js

Now we can see our application in the browser at

http://localhost:8080 and http://localhost:8080/about. Our application is set up and we have to define our view files and see how EJS works there.

EJS Partials footer.ejs, head.ejs, header.ejs

Like a lot of the applications we build, there will be a lot of code that is reused. We’ll call those

partials and define three files we’ll use across all of our site: head.ejs, header.ejs, and footer.ejs. Let’s make those files now.

<!-- views/partials/head.ejs -->

<meta charset="UTF-8">
<title>Super Awesome</title>

<!-- CSS (load bootstrap from a CDN) -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<style>
    body    { padding-top:50px; }
</style>
<!-- views/partials/header.ejs -->

<nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">

        <div class="navbar-header">
            <a class="navbar-brand" href="#">
                <span class="glyphicon glyphicon glyphicon-tree-deciduous"></span>
                EJS Is Fun
            </a>
        </div>

        <ul class="nav navbar-nav">
            <li><a href="/">Home</a></li>
            <li><a href="/about">About</a></li>
        </ul>
      
    </div>
</nav>
<!-- views/partials/footer.ejs -->

<p class="text-center text-muted">© Copyright 2014 The Awesome People</p>

Using EJS Partials

We have our partials defined now. All we have to do is call them in the files that we need them. Let’s go into

index.ejs and about.ejs and use them in there. We will also define the full width and sidebar layouts here using the good old Bootstrap grid. Using Partials The syntax to use an EJS partial is: <% include FILENAME %>. The path to the partial is relative to the current file.

<!-- views/pages/index.ejs -->

<!DOCTYPE html>
<html lang="en">
<head>
    <% include ../partials/head %>
</head>
<body class="container">

    <header>
        <% include ../partials/header %>
    </header>

    <main>
        <div class="jumbotron">
            <h1>This is great</h1>
            <p>Welcome to templating using EJS</p>
        </div>
    </main>

    <footer>
        <% include ../partials/footer %>
    </footer>
    
</body>
</html>

Now we can see our defined view in the browser at

http://localhost:8080.

node-ejs-templating-index
<!-- views/pages/about.ejs -->

<!DOCTYPE html>
<html lang="en">
<head>
    <% include ../partials/head %>
</head>
<body class="container">

    <header>
        <% include ../partials/header %>
    </header>

    <main>
        <div class="row">
            <div class="col-sm-8">
            
                <div class="jumbotron">
                    <h1>This is great</h1>
                    <p>Welcome to templating using EJS</p>
                </div>
                
            </div>
            <div class="col-sm-4">
                
                <div class="well">
                    <h3>Look I'm A Sidebar!</h3>
                </div>

            </div>
        </div>
    </main>

    <footer>
        <% include ../partials/footer %>
    </footer>
    
</body>
</html>

If we visit

http://localhost:8080/about, we can see our about page with a sidebar!

node-ejs-templating-about

Let’s move on and start using EJS for passing data from our Node application to our views.

Passing Data to Views

Let’s define some basic variables and a list to pass to our home page. Go back into your

server.js file and add the following inside your app.get('/') route.

// server.js

// index page 
app.get('/', function(req, res) {
    var drinks = [
        { name: 'Bloody Mary', drunkness: 3 },
        { name: 'Martini', drunkness: 5 },
        { name: 'Scotch', drunkness: 10 }
    ];
    var tagline = "Any code of your own that you haven't looked at for six or more months might as well have been written by someone else.";

    res.render('pages/index', {
        drinks: drinks,
        tagline: tagline
    });
});

We have created a list called

drinks and a simple string called tagline. Let’s go into our index.ejs file and use them.

Single Variable

To echo a single variable, we just use

<%= tagline %>. Let’s add this to our index.ejs file:

<!-- views/pages/index.ejs -->
...
<h2>Variable</h2>
<p><%= tagline %></p>
...

Looping Over Data

To loop over our data, we will use

.forEach. Let’s add this to our view file:

<!-- views/pages/index.ejs -->
...
<h2>Loop</h2>
<ul>
    <% drinks.forEach(function(drink) { %>
        <li><%= drink.name %> - <%= drink.drunkness %></li>
    <% }); %>
</ul>
...

Now we can see in our browser the new information we have added!

node-ejs-templating-variables

Advanced Layouts

Currently, EJS doesn’t support the ability to have layouts. So far we have just brought in other partials, but not really used layouts the way we would expect templating to work (extending a layout file and passing a view file into that). There have been projects in the past to try to bring templating to EJS. The two main projects are

EJS Locals and EJS Express Layouts. These provide the ability to define different layouts like a sidebar layout and a full width layout and then call those on the fly. Sadly, EJS Locals is no longer maintained and EJS Express Layouts doesn’t work with Express 4 at the time of this writing. Hopefully that will change in the future.

Conclusion

EJS let’s us spin up quick applications when we don’t need anything too complex. By using partials and having the ability to easily pass variables to our views, we can build some great applications quickly.

Chris Sevilleja

Co-founder of Scotch.io. Slapping the keyboard until something good happens.