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.
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.
Before diving into EJS, ensure you have Node.js installed on your machine. You can download it from nodejs.org.
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
Install Express.js and EJS using npm:
npm install express ejs
Create the following directory structure in your project folder:
express-ejs-demo/
āāā app.js
āāā views/
ā āāā index.ejs
ā āāā about.ejs
āāā public/
āāā styles.css
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}`);
});
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>
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;
}
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 provides a simple syntax for embedding JavaScript within HTML. Here are some common features:
Use <%= %> to embed variables in your templates:
<p>Your name is <%= name %>.</p>
Use <% if %>, <% else %>, and <% endif %> for conditional rendering:
<% if (isLoggedIn) { %>
<p>Welcome back, <%= user.name %>!</p>
<% } else { %>
<p>Please log in.</p>
<% } %>
Use <% for %> or <% forEach %> to iterate over arrays:
<ul>
<% users.forEach(function(user) { %>
<li><%= user.name %></li>
<% }); %>
</ul>
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>
EJS doesn't natively support layouts like some other templating engines (e.g., Pug). However, you can implement a simple layout system using partials:
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>
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>
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}`);
});
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!