2023-05-01 | Tag: Ejs
Learn how to use Ejs template engine and how to create a simple Ejs template.
EJS (Embedded JavaScript) is a templating engine for Node.js applications. It allows you to embed JavaScript into your HTML to create dynamic and reusable templates, making it ideal for server-side rendering of web pages.
Why Use EJS?
Key Features of EJS:
- **Simple Syntax**: EJS uses plain JavaScript within templates.
- **Reusable Components**: Break your UI into reusable pieces with partials.
- **Logic in Templates**: Include JavaScript logic like loops and conditionals directly in your views.
- **Fast and Lightweight**: Minimal overhead compared to other templating engines.
- **Wide Adoption**: Easily integrates with Express and other Node.js frameworks.
Steps to Set Up EJS in Your Project:
mkdir ejs-example && cd ejs-example
npm init -y
npm install express ejs
Example: Configuring EJS in Express
const express = require('express');
const app = express();
// Set EJS as the view engine
app.set('view engine', 'ejs');
// Serve static files
app.use(express.static('public'));
// Define a route
app.get('/', (req, res) => {
res.render('index', {
title: 'Home Page',
user: { name: 'John Doe', role: 'Admin' },
items: ['Node.js', 'Express', 'EJS']
});
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Basic EJS Syntax
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1>Welcome, <%= user.name %>!</h1>
<p>Your role is: <%= user.role %>.</p>
<ul>
<% items.forEach(item => { %>
<li><%= item %></li>
<% }); %>
</ul>
</body>
</html>
Example: Using Partials
// In a layout.ejs file:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<% include header %>
<main>
<%- body %>
</main>
<% include footer %>
</body>
</html>
// In header.ejs:
<header><h1>My Website</h1></header>
// In footer.ejs:
<footer><p>© 2025 My Website</p></footer>
Escaping Output (Prevents XSS):
<%= userInput %> <!-- Escapes HTML to prevent XSS -->
Unescaped Output (Use with Caution):
<%- userInput %> <!-- Does not escape HTML -->
Example: Conditional Logic in EJS
<% if (user.role === 'Admin') { %>
<p>Welcome, Admin!</p>
<% } else { %>
<p>Welcome, Guest!</p>
<% } %>
Example: Iterating Over an Array
<ul>
<% items.forEach(item => { %>
<li><%= item %></li>
<% }); %>
</ul>
Example: Handling Errors with EJS
// Middleware for 404 errors
app.use((req, res, next) => {
res.status(404).render('404', { title: 'Page Not Found' });
});
// Middleware for server errors
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).render('500', { title: 'Server Error' });
});
EJS is an excellent choice for server-side rendering in Node.js applications, offering simplicity, flexibility, and robust features.