What is EJS
EJS (Embedded JavaScript) is a templating engine that allows you to generate HTML with dynamic content in Express.js applications. It lets you embed JavaScript code within your HTML to render data dynamically, which is especially useful for building web pages that need to present data from a server or handle user inputs.
Using EJS with Express.js
Here’s a step-by-step guide to integrating EJS with Express.js:
1. Install EJS
First, you need to install EJS and Express in your project. If you haven't already set up your project, you can do so with the following commands:
npm init -y # Initialize a new Node.js project if you haven’t already
npm install express ejs
2. Set Up Express and EJS
Create a basic Express application and configure it to use EJS as the view engine.
Example Setup:
Create a basic Express application:
const express = require('express'); const app = express(); const path = require('path'); // Set EJS as the view engine app.set('view engine', 'ejs'); // Set the directory where the views are located app.set('views', path.join(__dirname, 'views')); app.get('/', (req, res) => { res.render('index', { title: 'Home Page', message: 'Welcome to EJS with Express!' }); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
Create the
views
directory:Inside your project directory, create a folder named
views
. This is where your EJS templates will reside.mkdir views
Create an EJS template:
Inside the
views
directory, create a file namedindex.ejs
.<!-- views/index.ejs --> <!DOCTYPE html> <html> <head> <title><%= title %></title> </head> <body> <h1><%= message %></h1> <p>This is a simple example of using EJS with Express.js.</p> </body> </html>
In this example:
<%= title %>
: This syntax is used to output the value of thetitle
variable into the HTML.<%= message %>
: This outputs the value of themessage
variable.
3. Render EJS Templates
To render an EJS template, use the res.render()
method in your route handlers. This method takes two arguments:
- The name of the EJS file (without the
.ejs
extension). - An object containing data to be passed to the template.
Example:
app.get('/', (req, res) => {
res.render('index', {
title: 'Home Page',
message: 'Welcome to EJS with Express!'
});
});
This renders the index.ejs
template and passes the title
and message
variables to it.
4. Using EJS Features
EJS supports various features to enhance your templates:
Variable Output:
<p>Hello, <%= user.name %>!</p>
JavaScript Code:
<% if (user.isAdmin) { %> <p>Welcome, Admin!</p> <% } %>
Loops:
<ul> <% items.forEach(item => { %> <li><%= item %></li> <% }) %> </ul>
Includes:
<%- include('header') %> <p>Main content here</p> <%- include('footer') %>
In this example, header.ejs
and footer.ejs
are included in the main template. Note the use of <%- %>
for including raw HTML content.
5. Error Handling and Debugging
When working with EJS, you may encounter issues with rendering or template syntax. Here are some tips:
- Check Template Paths: Ensure that the
views
directory is correctly specified and that the template files are in the right location. - Validate Syntax: Make sure that your EJS syntax is correct and that variables used in templates are properly passed from your route handlers.
- Inspect Errors: If there’s an error, Express will typically display a detailed message with the problem. Review the error messages to troubleshoot issues.
Summary
- Install EJS: Add EJS and Express to your project.
- Configure Express: Set EJS as the view engine and specify the views directory.
- Create Templates: Write EJS templates with dynamic content.
- Render Templates: Use
res.render()
to render EJS templates with data. - Use Features: Leverage EJS features like includes, loops, and conditional statements.
EJS provides a powerful way to build dynamic web pages with Express.js by embedding JavaScript directly in your HTML templates.