Using EJS in Node.js Application

EJS or Embedded JavaScript is a simple templating language which helps you to generate HTML markup with plain JavaScript. It is known for its fast development time,simple syntax, speedy execution, easy debugging etc. When you want to use EJS in your Node.js application, set the value of ‘view engine’ parameter to ‘ejs’ as shown below.

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

This request goes to a function in the backend of your application. When the function is called it renders the ejs file.

res.render('demo', {data:data})

It will return JSON data. The demo.ejs file looks like:

<html>

  <body>

  <br/>

    <h2>EJS Demo!!!</h2>

    <div>Name : <%= data.name%></div>

    <div>Age : <%= data.age%></div>

  </body>

</html>


Output:

Name:Sakshi

Age: 25


Now we will see some useful EJS tags.

<% >  - All JavaScript code will be executed when you type JavaScript inside this tag. It makes the usage of loops, if/else, switch statements easier. 

<table>

        <tr>

          <th>Name</th>

          <th>Age</th>

          <th>Email</th>

        </tr>

<% result.forEach(function(obj){ %>

        <tr>

          <td><%=obj.name%></td>

          <td><%=obj.age%></td>

          <td><%=obj.email%></td>

        </tr>

        <%})%>

</table>


<%= > -  The value of variables present inside this tag will be displayed as it is.

<%- >  -  This tag will render the HTML code inside it.

 Eg: JSON data = {myPage : “<html><body><h3>Hello World</h3></body></html>”}

To render this code use the following html code.

<div><%- myPage></div>

<%== > -  It is used to include templates in other templates