Introduction
One of the powerful features of Express.js is its ability to render dynamic HTML content using templating engines. Templating engines allow you to inject dynamic data into HTML views, making it possible to serve different content based on the user’s request. This is particularly useful for building dynamic websites or web applications that need to update content based on user input, server-side logic, or database queries.
In this post, we will focus on EJS (Embedded JavaScript) as the templating engine for Express.js. EJS is one of the most popular and straightforward templating engines for Node.js, and it integrates seamlessly with Express. You will learn how to set up EJS in an Express.js application, pass data from the server to the view, and generate reusable HTML templates.
By the end of this post, you’ll have a solid understanding of how to use EJS to render dynamic content and build more interactive and data-driven web applications.
What is EJS?
EJS stands for Embedded JavaScript, and it is a simple templating engine that enables you to inject JavaScript into HTML files. The core feature of EJS is its ability to embed JavaScript logic inside an HTML document. This allows you to generate dynamic content from the server side, such as user-specific information, lists of items, or results from a database query.
Why Use EJS?
- Easy to Learn and Use: EJS is very similar to regular HTML, with the ability to inject dynamic data using
<%= %>
syntax. - Lightweight: EJS is simple, fast, and doesn’t require extensive setup or configuration.
- Flexibility: EJS allows you to use JavaScript directly in the templates, making it highly customizable and easy to extend.
- Seamless Integration with Express: EJS integrates perfectly with Express.js, making it a great choice for rendering server-side views.
Setting Up EJS in an Express.js Application
Before you can use EJS in an Express application, you need to install the ejs
package and configure Express to use it as the view engine. Let’s walk through the setup process:
Step 1: Install EJS
You can install EJS using npm (Node Package Manager). In your project directory, run the following command:
npm install ejs
This will add EJS to your project’s dependencies.
Step 2: Configure Express to Use EJS
Once EJS is installed, you need to tell Express to use it as the view engine. Open your Express application’s main file (e.g., app.js
or server.js
) and add the following lines:
const express = require('express');
const app = express();
// Set EJS as the view engine
app.set('view engine', 'ejs');
// Set the directory for views (optional, defaults to "views")
app.set('views', path.join(__dirname, 'views'));
This tells Express to use EJS for rendering views. By default, Express looks for a folder named views
to store your template files. You can customize this location if needed.
Step 3: Creating EJS Template Files
Now that EJS is set up, you can start creating EJS template files. These files typically have the .ejs
extension and contain a mix of static HTML and dynamic JavaScript.
Create a views
folder in your project directory (if it doesn’t already exist), and inside it, create a new file called index.ejs
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= title %></title>
</head>
<body>
<h1><%= message %></h1>
<p>Welcome to our website!</p>
</body>
</html>
In this template, the <%= title %>
and <%= message %>
placeholders will be replaced with data passed from the server.
Step 4: Rendering the EJS Template in Express
To render the index.ejs
file with dynamic data, define a route in your Express app and pass data to the view:
app.get('/', (req, res) => {
res.render('index', { title: 'Home Page', message: 'Hello, EJS!' });
});
In this example:
- The
res.render('index')
function renders theindex.ejs
template. - The second argument to
res.render()
is an object that contains the data you want to pass to the template. In this case, we are passing atitle
andmessage
property.
When a user visits the root URL (/
), Express will render the index.ejs
file and inject the title
and message
values into the HTML.
Rendering Dynamic Content with EJS
One of the key features of EJS is the ability to insert dynamic data into templates. This makes it perfect for rendering content that changes based on server-side logic, user input, or data from a database.
Here are some common ways to work with dynamic content in EJS:
1. Variables
You can pass variables to your EJS templates and use them to dynamically generate content. Here’s an example:
app.get('/greeting', (req, res) => {
const name = 'John';
res.render('greeting', { title: 'Greeting Page', name: name });
});
And in the greeting.ejs
template, you can use the name
variable:
<h1>Hello, <%= name %>!</h1>
When the user visits /greeting
, the name
will be injected into the template, resulting in the following output:
<h1>Hello, John!</h1>
2. Conditionals
EJS supports basic JavaScript syntax, including conditionals. You can use if
statements to display content based on conditions:
app.get('/user', (req, res) => {
const isLoggedIn = true;
res.render('user', { title: 'User Page', isLoggedIn: isLoggedIn });
});
And in the user.ejs
template:
<% if (isLoggedIn) { %>
<h1>Welcome, User!</h1>
<% } else { %>
<h1>Please log in</h1>
<% } %>
If isLoggedIn
is true
, the first <h1>
will be displayed. If isLoggedIn
is false
, the second <h1>
will be shown.
3. Loops
EJS also supports loops, which are useful for rendering lists or repeating content. For example, you can render a list of users like this:
app.get('/users', (req, res) => {
const users = ['Alice', 'Bob', 'Charlie'];
res.render('users', { title: 'User List', users: users });
});
In the users.ejs
template, you can loop through the users
array:
<ul>
<% users.forEach(function(user) { %>
<li><%= user %></li>
<% }); %>
</ul>
This will generate the following HTML:
<ul>
<li>Alice</li>
<li>Bob</li>
<li>Charlie</li>
</ul>
Reusable Templates with Partials
A common feature in templating engines is the ability to reuse common sections of HTML, like headers, footers, and navigation bars. In EJS, this can be achieved using partials.
To use partials, create separate EJS files for reusable sections, like header.ejs
and footer.ejs
, and include them in your main template using the <%- include %>
tag.
Example: header.ejs
<header>
<h1><%= title %></h1>
<nav>
<a href="/">Home</a> | <a href="/about">About</a>
</nav>
</header>
Example: footer.ejs
<footer>
<p>&copy; 2023 My Website</p>
</footer>
Main Template: index.ejs
<%- include('header', { title: 'Home Page' }) %>
<p>Welcome to my site!</p>
<%- include('footer') %>
When rendered, the contents of header.ejs
and footer.ejs
will be inserted into the main template.
Passing Data from a Database to EJS Templates
In real-world applications, you often need to render dynamic content based on data from a database. Express and EJS make it easy to integrate databases such as MongoDB, MySQL, or PostgreSQL.
For example, if you’re using MongoDB with the Mongoose library, you can fetch data from a collection and pass it to an EJS template:
const mongoose = require('mongoose');
const User = require('./models/User'); // Assuming User model is defined
app.get('/users', async (req, res) => {
try {
const users = await User.find();
res.render('users', { title: 'User List', users: users });
} catch (err) {
console.log(err);
res.status(500</code></pre>
Leave a Reply