What is EJS?
EJS (Embedded JavaScript) is a simple templating language that lets you generate HTML markup with plain JavaScript. It allows you to include dynamic content and logic in your HTML pages without the overhead of a full client-side framework.
Setting Up Your Node Application
First, ensure that you have Node.js and npm installed on your system. Create a new directory for your project and initialize it:
mkdir my-ejs-app cd my-ejs-app npm init -y
Installing Express and EJS
Install Express and EJS via npm:
npm install express ejs
Configuring Express to Use EJS
Create a file named app.js
and set up your Express server to use EJS as the templating engine:
const express = require('express'); const app = express(); const PORT = process.env.PORT || 3000; // Set EJS as the templating engine app.set('view engine', 'ejs'); // Define a route app.get('/', (req, res) => { // Pass dynamic data to the EJS template res.render('index', { title: 'Home Page', message: 'Hello, EJS!' }); }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
Creating Your EJS Template
Create a directory called views
in your project root. Inside the views
folder, create a file named index.ejs
:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title><%= title %></title> </head> <body> <h1><%= message %></h1> <p>Welcome to your EJS templated page!</p> </body> </html>
Here, <%= %>
is used to output the dynamic content passed from your Express route. You can also use <% %>
for running JavaScript code without outputting it directly.