EJS (Embedded JavaScript Templates)
Overview
- EJS: A templating language to generate HTML using plain JavaScript.
- Purpose: Simplifies generating HTML markup with JavaScript by separating view logic (HTML) from control logic (routing).
Getting Started
Install EJS
- Run
npm install ejs
in your project directory.
npm install ejs
- This updates package.json with the EJS dependency:
"dependencies": {
"ejs": "...",
"express": "..."
}
Configure EJS in Express:
- Set the view engine to EJS in your Express app:
app.set('view engine', 'ejs');
- Set the views directory to the
views
folder:
app.set('views', path.join(__dirname, 'views'));
Create EJS Files
- Create an EJS file (e.g.,
viewData.ejs
) in theviews
directory. - Use the
.ejs
extension for EJS files.
<!-- views/viewData.ejs -->
<!DOCTYPE html>
<html>
<head>
<title>View Data</title>
</head>
<body>
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
<th>Occupation</th>
<th>Company</th>
</tr>
<tr>
<td><%= data.name %></td>
<td><%= data.age %></td>
<td><%= data.occupation %></td>
<td><%= data.company %></td>
</tr>
</table>
</body>
</html>
Update the Route to Render the EJS Template:
- Use
res.render()
to render the EJS file:
app.get('/viewData', (req, res) => {
let someData = {
name: 'John',
age: 23,
occupation: 'developer',
company: 'Scotiabank',
};
res.render('viewData', { data: someData });
});
EJS Syntax and Delimiters
Delimiters: Special tags used to embed JavaScript within HTML.
<%= ... %>
: Renders and HTML escapes a value.<%- ... %>
: Renders a value without HTML escaping.<%# ... %>
: Adds comments that won't be rendered in HTML.<% ... %>
: Used for scripting logic (e.g., loops, conditionals).
Common Features
Includes / Partials
- Reusability: Separate reusable blocks (e.g., headers, footers) into partials.
- Example: Creating a header partial:
<!-- views/partials/header.ejs -->
<h1>EJS Practice - <%= page %></h1>
<hr />
<a href="/">Home</a> | <a href="/about">About</a> | <a href="/viewData">View Data</a>
<hr />
<br />
- Example: Including a Partial:
<!-- views/index.ejs -->
<%- include('partials/header', {page: '/viewData'}) %>
Logic and Iteration
- If/Else Statements: Conditionally render HTML.
<% if (data.visible) { %>
<tr>
<td><%= data.name %></td>
<td><%= data.age %></td>
<td><%= data.occupation %></td>
<td><%= data.company %></td>
</tr>
<% } else { %>
<tr>
<td colspan="4">User: '<%= data.name %>' has hidden their information</td>
</tr>
<% } %>
- Loops: Iterate over collections to render data.
<% data.forEach(user => { %>
<tr>
<td><%= user.name %></td>
<td><%= user.age %></td>
<td><%= user.occupation %></td>
<td><%= user.company %></td>
</tr>
<% }) %>
Layouts
- Structure: Common layout includes (e.g., headers, footers) across multiple pages.
<body>
<%- include('header') %>
<%# Page Content / Data Here %>
<%- include('footer') %>
</body>
- Customization: Pass data to partials to customize them per page.
<%- include('partials/header', {page: '/viewData'}) %>