Introduction
EJS (Embedded JavaScript) is a template engine used with NodeJS to add dynamic content to HTML documents. In this article, we will explore the basics of EJS and how you can leverage it in your Nodejs applications.
What is EJS?
When building web applications using Nodejs, you often need to dynamically generate HTML content. However, as the project grows, we obtain cumbersome and maintenance-challenging applications. This is where template engines come in handy. They make it easy to configure and manage dynamic content. EJS (Embedded JavaScript) is one of the template engines that works seamlessly with Nodejs.
EJS is a simple templating language that enables dynamic content creation in JavaScript. It allows you to embed JavaScript code inside your HTML and makes it easier to create dynamic content on the server side. With EJS, you can make your code more readable and maintainable by including variables, loops, conditionals, and more directly in your HTML files.
How To Integrate EJS and NodeJS
Integrating Node.js and EJS is quite simple. First, you need to install the EJS module in your project. Now, let’s integrate EJS into our application by creating a nodejs application from scratch.
Setting Up Your Node.js Project
Before diving into EJS, let’s set up a basic Node.js project. Ensure that Node.js is installed on your machine. Create a new project folder and run the following commands in your terminal:
mkdir ejs-nodejs-guide
cd ejs-nodejs-guide
npm init -y
This will initialize a new Node.js project with a package.json
file. Now, install the necessary dependencies:
npm install express ejs
This installs the Express web framework and EJS template engine. Express is a popular choice for building web applications in Node.js, and EJS integrates seamlessly with it.
Creating an Express App with EJS
Now, let’s create a simple Express app that uses EJS for rendering dynamic content. Create an index.js
file in your project folder and add the following code:
const express = require('express');
const app = express();
const port = 3000;
// Set EJS as the view engine
app.set('view engine', 'ejs');
// Serve static files from the 'public' folder
app.use(express.static('public'));
// Define a route that renders an EJS template
app.get('/', (req, res) => {
const data = {
pageTitle: 'EJS Node.js Guide',
message: 'Welcome to the EJS beginner\'s guide!'
};
res.render('index', data);
});
// Start the server
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
In the code above, we set EJS as the view engine for Express using app.set('view engine', 'ejs')
. We also configure the server to serve static files from a ‘public’ folder using express.static('public')
. This is where you can store your client-side assets like CSS and JavaScript files.
Creating Your First EJS Template
Now, let’s create an EJS template. Inside your project folder, create a ‘views’ folder and add an index.ejs
file with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= pageTitle %></title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<h1><%= message %></h1>
</body>
</html>
In this template, <%= pageTitle %>
and <%= message %>
are EJS tags used to embed dynamic content. When the template is rendered, these tags will be replaced with the corresponding values provided in the res.render
method.
Running Your Node.js App
Before running your app, create a ‘public’ folder in your project directory and add a simple CSS file named styles.css
:
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 50px;
}
h1 {
color: #3498db;
}
Now, start your Node.js server by running:
node index.js
Visit http://localhost:3000 in your web browser, and you should see your EJS template rendered with the dynamic content.
Understanding EJS Tags
EJS tags are a crucial aspect of using EJS effectively. They allow you to embed JavaScript code directly within your HTML templates. Here are some commonly used EJS tags:
<%= %>
: Outputs the value of the JavaScript expression inside the tags to the HTML. Used for displaying dynamic content.<% %>
: Executes the JavaScript code inside the tags without outputting anything. Used for control flow and logic.htmlCopy code
<% if (user.isAdmin) { %> <p>Welcome, Admin!</p> <% } else { %> <p>Welcome, User!</p> <% } %>
<%- %>
: Similar to<%= %>
, but it outputs the unescaped raw HTML. Be cautious when using this to prevent cross-site scripting (XSS) vulnerabilities.<%# %>
: Comment tag, used for adding comments in your EJS templates.htmlCopy code
<%# This is a comment %>
Passing Data to EJS Templates
In the earlier example, we passed data to the EJS template using the res.render
method. The data
object contained properties like pageTitle
and message
, which were then accessed in the EJS template.
const data = {
pageTitle: 'EJS Node.js Guide',
message: 'Welcome to the EJS beginner\'s guide!'
};
res.render('index', data);
You can pass various types of data to your templates, including strings, numbers, arrays, and objects. Accessing this data in the template allows you to dynamically generate content based on the provided values.
Looping and Conditionals in EJS
EJS makes it easy to incorporate loops and conditionals directly in your templates. Let’s modify our index.ejs
file to include a loop and a conditional statement:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= pageTitle %></title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<h1><%= message %></h1>
<% if (users.length > 0) { %>
<ul>
<% users.forEach(user => { %>
<li><%= user.name %></li>
<% }); %>
</ul>
<% } else { %>
<p>No users available.</p>
<% } %>
</body>
</html>
In this example, we use an if-else statement to check if there are any users in the users
array. If there are, we loop through the array using the forEach
method and display each user’s name. If the array is empty, a message indicating no users are available is shown.
Partials in EJS
Partials are reusable components or templates that can be included in multiple EJS files. They are useful for organizing your code and avoiding redundancy. Let’s create a simple partial for a header and include it in our index.ejs
file.
First, create a ‘partials’ folder inside the ‘views’ folder, and add a file named _header.ejs
:
<!-- _header.ejs -->
<header>
<h1><%= pageTitle %></h1>
</header>
Now, modify your index.ejs
file to include the header partial:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= pageTitle %></title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<% include ./partials/_header %>
<h1><%= message %></h1>
<% if (users.length > 0) { %>
<ul>
<% users.forEach(user => { %>
<li><%= user.name %></li>
<% }); %>
</ul>
<% } else { %>
<p>No users available.</p>
<% } %>
</body>
</html>
In the index.ejs
file, the <% include ./partials/_header %>
tag includes the header partial at that position in the template. This promotes code reusability and makes your templates more modular.
Conclusion
You’ve now built a basic Node.js application using the EJS template engine. You’ve learned how to set up an Express server, use EJS for rendering dynamic content, and incorporate features like loops, conditionals, and partials.
As you continue working with EJS and Node.js, you’ll discover more advanced features and techniques. Consider exploring additional EJS functionalities, such as custom layouts, filters, and error handling, to enhance your web development projects.
Thank you for reading.