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
sam smith
16 Apr 2023
I just want the whole world to know about this spell caster I met two weeks ago, I cannot say everything he has done for me my wife left me 3 years ago left with my kids I was going through online when I meant this wonderful man's testimony online I decided to give it a try and my wife is back to me now and we are happily married again cause is too much to put in writing all I can say is thank you very much am very happy Contact him today on oseremenspelltemple@gmail.com or whatsapp him on +2348136482342. www.facebook.com/Dr-odion-spell-temple-110513923938220