Using EJS in your Node.JS application

31 / Jan / 2014 by Sakshi Tyagi 5 comments

EJS as the name implies embedded JavaScript, is a JavaScript templating library used to render html code along with JSON data in an easy and clean way.

In a Node.JS application(here we are using an express application), you need to set the value of ‘view engine’ parameter to ‘ejs’.

var app = express();
app.set(‘view engine’, ‘ejs’);

Now request goes to backend, a function is called there which renders the ejs file:
[js] res.render(‘demo’, {data:data})[/js]

Lets say it returns JSON data like:
{name: 'Sakshi', age : '24', hobbies: ['blogging', 'reading']}

Now the final step, Rendering the ejs file. Our demo.ejs looks like:

<h2>EJS Demo!!!</h2>
<div>Name : <%=></div>
<div>Age : <%= data.age%></div>

Name: Sakshi
Age: 24

Some useful ejs tags are:
1. <% > : This tag executes all the JavaScript code present inside it. So we can easily use for loops, if/else statements, switch statements and variable declarations inside the EJS template.
For examlpe:
<% result.forEach(function(obj){ %>

2. <%= > : The value of the variable present between this tag is printed as it is given by JSON data.

3. <%- > : This tag renders the actual html code present between it.
For example:
JSON data = {myPage : “<html><body><h3>Hello World</h3></body></html>”}

So for rendering this html code we use:
<div><%- myPage></div>

4. <%== > : This tag is commonly used to include templates in other templates.

NOTE: EJS also allow us to include another ejs template or file into our current ejs page. This can be done using <% include otherPage.ejs %>.

Hope this will help 🙂


Tag -

ejs node.js

comments (5)

  1. Ganse

    Hey ! I am trying to call a function onClick of button. The function is present in “” tags in my ejs file. Have tried several ways to do this. But unable to get a result. Can you please help me out ? Any help would be appreciated. Thank you !

    1. Sakshi Tyagi

      You can use if else statement in ejs like :

      <% if(!sessionUser){%>
      <a href="javascript:void(0)" onclick="createCookie()" class="btn btn-info btn-large">Sign In</a>
      <% } else{ %>
      <a href="/" class="btn btn-info btn-large">Home</a>


Leave a Reply

Your email address will not be published. Required fields are marked *