Node JS EJS and express js


EJS (Embedded JavaScript) is a templating engine that allows you to generate HTML dynamically by embedding JavaScript logic within your HTML. It integrates smoothly with Express.js and Node.js for server-side rendering of views. Here’s a step-by-step guide on how to use EJS with Express and Node.js:

1. Install EJS

First, you need to install EJS and Express in your Node.js project. You can do this using npm:

npm install express ejs

2. Set Up Your Express Application

Create a basic Express application if you don’t already have one. Here’s a simple setup:

app.js or index.js:

const express = require('express'); const app = express(); const port = 3000; // Set EJS as the templating engine app.set('view engine', 'ejs'); app.set('views', __dirname + '/views'); // Set the directory for views // Define a route app.get('/', (req, res) => { res.render('index', { title: 'Home Page', message: 'Hello, world!' }); }); // Start the server app.listen(port, () => { console.log(`Server is running at http://localhost:${port}`); });

3. Create EJS Templates

Create a views directory in your project root (or whatever directory you specified in app.set('views', ...)), and then create an EJS template file inside it.

views/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> </head> <body> <h1><%= message %></h1> <p>Welcome to the EJS templating example!</p> </body> </html>

4. Rendering EJS Templates

In your Express route handlers, use the res.render method to render the EJS templates. Pass data to the template as an object, and this data will be available in the EJS template.

Example Route:

app.get('/about', (req, res) => { res.render('about', { title: 'About Page', content: 'This is the about page.' }); });

5. Dynamic Data and Control Flow

EJS allows you to use JavaScript code within your templates for dynamic content and control flow.

Example of Dynamic Data and Control Flow in views/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> </head> <body> <h1><%= title %></h1> <p><%= content %></p> <% if (users && users.length) { %> <ul> <% users.forEach(user => { %> <li><%= user %></li> <% }); %> </ul> <% } else { %> <p>No users found.</p> <% } %> </body> </html>

Updated Route Handler to Pass Data:

app.get('/about', (req, res) => { const users = ['Alice', 'Bob', 'Charlie']; res.render('about', { title: 'About Page', content: 'This is the about page.', users: users }); });

6. Handling Static Files

If you need to serve static files (like CSS or JavaScript), use the express.static middleware.

Example:

app.use(express.static('public'));

Place your static files in the public directory. For instance, if you have a CSS file located at public/styles.css, you can link to it in your EJS templates like this:

In views/index.ejs:

<link rel="stylesheet" href="/styles.css">

7. Advanced Features

Partials: Use EJS partials to include reusable templates (e.g., headers, footers).

Example of Partial:

Create a partial file views/partials/header.ejs:

<header> <h1>My Website</h1> <nav> <a href="/">Home</a> <a href="/about">About</a> </nav> </header>

Include the partial in your main EJS template:

In views/index.ejs:

<%- include('partials/header') %>

Layouts: For layout management, consider using a package like express-ejs-layouts.

Installation:

npm install express-ejs-layouts

Usage:

const expressLayouts = require('express-ejs-layouts'); app.use(expressLayouts); app.set('layout', 'layouts/main'); // Define the default layout

Create a layout file views/layouts/main.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> </head> <body> <%- body %> <!-- This will render the view content --> </body> </html>