Express Complete Tutorial : Part 2

Front end is product for the user. Does’nt matter how complex and well designed back-end you have, if your front-end lacks the user expectations then at some point it’s gonna fail. In previous tutorial we have configured the express.

In this tutorial i am going to explain how to use EJS to template your advanced web applications. For those who are confuse with HTML and EJS. EJS parse complete HTML without any issue, with that it also provide some cool features which i am gonna explain below.

Beauty of EJS is that you can use one template to perform multiple operations. if i create on EJS file and set the title, head, div ID etc coming from server. I can set it multiple times depending upon the routes call.

Passing data to View:

Look on below code. This code is just for example. It’s not working code. Let’s say from Express i have pass this data.

          res.render('index',{title:"Home page"});


In index.ejs i can simply do this to access title variable.

<title><%= title %></title>

In this way you can pass any important data from Server and access here. This is one of the coolest feature of EJS.

EJS partials: Dividing code into multiple parts

You can divide the EJS code into multiple files just like we do in PHP or Rails. You can include those partials files using

<% include FILENAME %>
     <% include('header.ejs') %>
      <% include('body.ejs') %>

Here is header.ejs partial code.

Hello World
<script src="jquery.js"></script>
...Your JavaScript code goes here.

Here is body.ejs partial code.

  <div id="login">
      <input type="TEXT" name="user_name" value=""><br>
      <input type="password" name="password" value=""><br>
      <input type="button" name="login" value="Login">

EJS filters:

Ejs provides “filters” which helps to modify data without writing JavaScript. By using filter, you can perform various operations on data. Operations such as:

  • Capitalise letter.
  • Downcase letter.
  • sort.
  • size.
  • length.

You can view complete list of filters here.

In next tutorial i am going to explain how to handle router of Express web applications.


Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126