Sitemap

Using EJS with Node JS

5 min readDec 6, 2017

--

As a developer we face challenges everyday. I am a backend developer and recently my boss wanted me to build a web app and told me to get my hands on front-end too. I was like “You are kidding right” ? I know learning new technologies is fun and one has to push himself to move forward. But I was not expecting this coming.

Anyways, There are various front-end technologies out their ( Angular JS and react JS to name a few ). But it requires both time and effort to have a command on them. You can also use AJAX to call your APIs and manipulate DOM everytime (Don’t do it, it’s obnoxious). But I suggest a better way it’s called “EJS”. EJS helps to generate HTML with the help of javascript. If you have used PHP before you can easily grab it because of the similarity in embedding tags in HTML. If you didn’t- hey, I am writing for you brother.

Before we start I would like to include that, this blog is totally based upon my experience. Yeah I’m honest…

So, Lets Get Started…

First thing first, we need package.json file with below code-

{
"name": "express-ejs",
"main": "server.js",
"dependencies": {
"ejs": "^2.5.7",
"express": "^4.16.2"
}
}

Now open terminal(OSX and ubuntu) or cmd(windows), go to the directory where our project contains package.json file and run-

npm install

Second, our folder structure-

Third, we need to configure server.js file (you can use any name for your file).

1 var express = require('express');
2 var app = express();
3 var ejs = require('ejs');
4 app.set('view engine', 'ejs');5 app.set('views',__dirname+'/frontend');6 app.use('/css', express.static(__dirname+'/frontend/css'));7 app.listen(8080); // 8080 is a port on which node server runs

Above lines are required in the server.js file to use EJS.
Line-4 tells which view engine to use. Here, It will use EJS rules while creating HTML.

At Line-5 we are just telling express “Hey express, look all of my template files(.ejs) at this path”. Here, in the second parameter, “__dirname” is a global variable which tells current location of our server.js file.

At Line-6 we are creating the route for our static files. We are telling “EJS” when you find any path that starts with “/css” (first parameter), find the following file in the “/frontend/css” folder (second parameter). I know it may confuse you, but it will make more sense later I promise.

Last, our route to use EJS template -

app.get('/index', function(req, res) {
res.render("index", { name: prince, hobbies: ['making coffee', 'talking'] });
});

Here, we are using res.render() to render HTML template that contains two parameters-
1. Filename (index.ejs) that we want to render.
2. Object, having key-values that we want to use locally in our template environment.

EJS first makes HTML on the server and then sends it to the client as a view.

Pheu…

Sharpening your weapon with some basics…

I want you to remember only two simple tags that are very important while working with EJS. Consider,

1. <%   %>
2. <%= %>

We use first tag pattern to write javascript code. All conditions, loops, initializations, expressions etc. goes straight here. Remember, JS and HTML codes are different and EJS helps to make HTML with the combination of both of them.

Get Prince Garg’s stories in your inbox

Join Medium for free to get updates from this writer.

We use second tag pattern to print something inside HTML dynamically. It could be a variable we passed as our “render()” object parameter or a variable we created with “<% %>” tag.

Now let’s play with our index.ejs

  1. “if” condition
<html>
<body>
<%
if(name === "prince") {
var message= "Its Good to see you...";
%>
<%= message %>
<%
}
%>
</body>
</html>

Output:

Press enter or click to view image in full size

Pay close attention to how we’re using both the tags inside our HTML to check if the condition is true, initialize variable and assign value inside “<% %>” tag. Then, print “message” using “<%= %>” tag and close “if” condition using “<% %>” tag at the end. Again, all your logics inside “<% %>” tag and printing by “<%= %>” tag.
Peace of cake…

2. Loops

<html>
<body>
<%
if(name === "prince") {
hobbies.forEach( function(hobby) {
%>
<input type="checkbox"
<% if(hobby === "talking") { %>
checked
<% } %>
/> <%= hobby %>
<%
});
}
%>
</body>
</html>

Output:

Press enter or click to view image in full size

Now we are taking advantage of the awesomeness of EJS by dynamically creating form input checkbox of hobbies by a for loop and mark it checked if the condition is true. You can also use “while” loop as well to accomplish the same task. So, what do think? I know it gets a bit ugly sometimes but it sure makes easy to get what you need.

3. Using environment variables inside <script> tag

Here comes some craziness, there may be some cases where you have to put value inside your scripts. Happened to me when I wanted to give a date value from my DB to my jQuery plugin in a specific format.
Behold,

<script>
alert("<%= name %>");
</script>

Output:

Press enter or click to view image in full size

Easy right? We just used our basics that’s all.

4. include-ing

To include repeatable parts in our current template we use include.
Consider, our new index.ejs with a link to our “style.css” stylesheet-

<html>
<body>
<head>
<meta charset="UTF-8">
<title>Awesome EJS</title>
<link href="/css/style.css" rel="stylesheet" />
</head>
<body>
<%
if(name === "prince") {
var message= "Its Good to see you...";
%>
<%= message %>
<%
}
%>
</body>
</html>

To demonstrate the working of “include”, we made a file- “header.ejs” and put our header information inside it. Separating code is a good practice, it will not only make our code look clean but also gives us the flexibility to maintain and reuse our code.

Our “header.ejs” file-

<meta charset="UTF-8">
<title>Awesome EJS</title>
<link href="/css/style.css" rel="stylesheet" />

And our new “index.ejs” using include-

<html>
<body>
<head>
<% include header %>
</head>
<body>
<%
if(name === "prince") {
var message= "Its Good to see you...";
%>
<%= message %>
<%
}
%>
</body>
</html>

Looks Great!. Now when there will be multiple templates file including our “header.ejs” file and you require using another css file in every template, you don’t have to copy-paste link tag in your templates. You just have to make a <link> tag inside “header.ejs” file and it will be included in all of your templates automatically.

Hope I could help you with this blog. Claps are the appreciations. I always look forward to hearing from you.

And always remember,
You are Awesome

--

--

Prince Garg
Prince Garg

Written by Prince Garg

Ethereum, Solidity, Ripple, Node JS, MongoDB, MySQL, Elasticsearch, express js, sails js, socket.io, Javascript