What is EJS?

EJS is JavaScript template or better be called as Embedded JavaScript template. EJS combines data and template to produce HTML. It is based on Ruby’s ERB i.e. Embedded Ruby.

A simple application of EJS with Node.JS 

Install the EJS template using npm(Node Packaged Modules):

| npm install ejs

After installing the ejs module, we have to create two files, one file(.js extension) with Node.js code and one file with EJS(.ejs extension) consuming the data given by the first file. The second file is more like a client and output can viewed over web browser at the specified url in the Node file

Below is the node.js code. 

var http = require(‘http’)
, ejs = require(‘ejs’);
// create http server
http.createServer(function (req, res) {
res.writeHead(200, {‘content-type’: ‘text/html’});
// data to render
var names = [‘Name 1’, ‘Name 2’, ‘Name 3’, ‘Name 4’, ‘Name 5’];
var title = ‘EJS template with Node.JS’;
// rendering the ejs file
ejs.renderFile(__dirname + ‘/views/simple.ejs’,
{title : title, names : names},
function(err, result) {
// render on success
if (!err) {
res.end(result);
}
// render or error
else {
res.end(‘An error occurred’);
console.log(err);
}
});
}).listen(8124);
console.log(‘Server running on 8124/’);

Code analysis:

1. Including http and ejs libraries.
2. Creating HTTP server with method ‘http.createServer()’
3. Data to be displayed on client is defined with variables as ‘names’ and ‘title’
4. EJS ‘renderFile’ method is invoked to execute the ejs file with data
5. A callback function is defined to display the data on success or error message on failure.
6. The server is listened to on port 8124

Below is the ejs code: 

<html>
<head>
<title><%= title %></title>
</head>
<body>
<h2>Data from Node</h2>
<% if (names.length) { %>
<ul> <% names.forEach(function(name){ %>
<li><%= name %></li> <% }) %>
</ul> <% } %>
</body>
</html>

Note: The angle brackets and percentage sign pairs () are used to delimit the EJS instructions

Steps to run this application:

1. Include the EJS library


2. Execute the node file

3. Open any browser and type the url: ‘http://localhost:8124’ and view the result.

References:

http://embeddedjs.com/
https://npmjs.org/

Download code

ejs