codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

Ā© 2026 codingstuff.io. All rights reserved.

Built with ā¤ļø for developers everywhere

/
/
All Tutorials
šŸš‚

Express.js

8 / 76 topics
7Using Templates with Express.js8EJS (Embedded JavaScript) Templates9Pug (formerly Jade) Templates10Handlebars Templates
Tutorials/Express.js/EJS (Embedded JavaScript) Templates
šŸš‚Express.js

EJS (Embedded JavaScript) Templates

Updated 2026-04-20
3 min read

EJS (Embedded JavaScript) Templates

Introduction

In this section, we will explore EJS (Embedded JavaScript) templates, a popular templating engine used with the Express.js framework. EJS allows you to embed JavaScript code within HTML files, making it easier to generate dynamic content for web applications.

What is EJS?

EJS stands for Embedded JavaScript. It's a simple templating language that lets you generate HTML with plain JavaScript. EJS templates are written in HTML and can include JavaScript variables, loops, conditionals, and functions directly within the template files.

Setting Up Express.js with EJS

Before diving into EJS, ensure you have Node.js installed on your machine. You can download it from nodejs.org.

Step 1: Initialize a New Node.js Project

Open your terminal and create a new directory for your project:

mkdir express-ejs-demo
cd express-ejs-demo

Initialize a new Node.js project:

npm init -y

Step 2: Install Express.js and EJS

Install Express.js and EJS using npm:

npm install express ejs

Step 3: Create the Basic File Structure

Create the following directory structure in your project folder:

express-ejs-demo/
ā”œā”€ā”€ app.js
ā”œā”€ā”€ views/
│   ā”œā”€ā”€ index.ejs
│   └── about.ejs
└── public/
    └── styles.css

Step 4: Set Up Express.js with EJS

Create the app.js file and set up a basic Express server:

// app.js
const express = require('express');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3000;

// Set the views directory
app.set('views', path.join(__dirname, 'views'));

// Set EJS as the templating engine
app.set('view engine', 'ejs');

// Serve static files from the public directory
app.use(express.static(path.join(__dirname, 'public')));

// Define routes
app.get('/', (req, res) => {
  res.render('index', { title: 'Home Page' });
});

app.get('/about', (req, res) => {
  res.render('about', { title: 'About Us' });
});

// Start the server
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Step 5: Create EJS Templates

Create the index.ejs and about.ejs files in the views directory:

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>
    <link rel="stylesheet" href="/styles.css">
</head>
<body>
    <h1>Welcome to the Home Page!</h1>
    <p>This is a simple EJS template example.</p>
</body>
</html>

about.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>
    <link rel="stylesheet" href="/styles.css">
</head>
<body>
    <h1>About Us</h1>
    <p>This is the about page.</p>
</body>
</html>

Step 6: Add Basic CSS

Create a simple styles.css file in the public directory:

/* styles.css */
body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 20px;
}

h1 {
    color: #333;
}

Step 7: Run Your Application

Start your Express.js server by running the following command in your terminal:

node app.js

Open your browser and navigate to http://localhost:3000 to see the home page, and http://localhost:3000/about to see the about page.

EJS Syntax

EJS provides a simple syntax for embedding JavaScript within HTML. Here are some common features:

Embedding Variables

Use <%= %> to embed variables in your templates:

<p>Your name is <%= name %>.</p>

Conditional Statements

Use <% if %>, <% else %>, and <% endif %> for conditional rendering:

<% if (isLoggedIn) { %>
    <p>Welcome back, <%= user.name %>!</p>
<% } else { %>
    <p>Please log in.</p>
<% } %>

Loops

Use <% for %> or <% forEach %> to iterate over arrays:

<ul>
  <% users.forEach(function(user) { %>
    <li><%= user.name %></li>
  <% }); %>
</ul>

Including Partials

Partials are reusable components that can be included in other templates. Create a partials directory inside the views folder and add an header.ejs file:

header.ejs

<header>
    <h1><%= title %></h1>
</header>

Include this partial in your main templates using <%- include %>

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>
    <link rel="stylesheet" href="/styles.css">
</head>
<body>
    <%- include('partials/header') %>
    <p>This is a simple EJS template example.</p>
</body>
</html>

Best Practices

  1. Separation of Concerns: Keep your business logic separate from your presentation logic. Use controllers to handle data and pass it to the views.
  2. Use Partials for Reusability: Break down your templates into smaller, reusable components using partials.
  3. Minimize Inline JavaScript: Avoid embedding complex JavaScript logic directly in your templates. Instead, use helper functions or middleware to preprocess data before passing it to the view.
  4. Cache Templates: In production, enable template caching to improve performance.

Advanced Features

Layouts with EJS

EJS doesn't natively support layouts like some other templating engines (e.g., Pug). However, you can implement a simple layout system using partials:

  1. Create a layout.ejs file in the views directory:

layout.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>
    <link rel="stylesheet" href="/styles.css">
</head>
<body>
    <%- include('partials/header') %>
    <div class="content">
        <%- body %>
    </div>
</body>
</html>
  1. Modify your index.ejs and about.ejs to extend the layout:

index.ejs

<% layout('layout'); %>

<p>This is a simple EJS template example.</p>

about.ejs

<% layout('layout'); %>

<p>This is the about page.</p>
  1. Update your app.js to use the layout:
// app.js
const express = require('express');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3000;

// Set the views directory
app.set('views', path.join(__dirname, 'views'));

// Set EJS as the templating engine
app.set('view engine', 'ejs');

// Serve static files from the public directory
app.use(express.static(path.join(__dirname, 'public')));

// Define routes
app.get('/', (req, res) => {
  res.render('index', { title: 'Home Page' });
});

app.get('/about', (req, res) => {
  res.render('about', { title: 'About Us' });
});

// Start the server
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Conclusion

EJS is a powerful and flexible templating engine that integrates seamlessly with Express.js. By following best practices and leveraging its features like partials and layouts, you can create maintainable and efficient web applications.

In the next section of our course, we will explore more advanced topics such as handling forms, integrating with databases, and deploying your application to production environments. Stay tuned!


PreviousUsing Templates with Express.jsNext Pug (formerly Jade) Templates

Recommended Gear

Using Templates with Express.jsPug (formerly Jade) Templates