Using EJS in your Node.JS application
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’.
[js]
var app = express();
app.set(‘view engine’, ‘ejs’);
[/js]
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:
[js]
<html>
<body>
<br/>
<h2>EJS Demo!!!</h2>
<div>Name : <%= data.name%></div>
<div>Age : <%= data.age%></div>
</body>
</html>
[/js]
Output:
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:
[js]
<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>
[/js]
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:
[js]
<div><%- myPage></div>
[/js]
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 🙂
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 !
Can you please provide me the code snippet you are executing? I’ll have look into it.
How can i use switch case statement in nodejs.
How can i use IF else statement in nodejs.
You can use if else statement in ejs like :
[js]
<% 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>
<%}%>
[/js]