0
0
Expressframework~5 mins

EJS template setup in Express

Choose your learning style9 modes available
Introduction

EJS helps you create web pages that change based on data. It mixes HTML with simple code to show dynamic content.

You want to show user names or messages on a webpage.
You need to build a website that updates content without rewriting HTML.
You want to separate your webpage design from your server code.
You are making a small to medium website with Express and want easy templates.
You want to reuse parts of your webpage like headers or footers.
Syntax
Express
const express = require('express');
const app = express();

app.set('view engine', 'ejs');

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

Use app.set('view engine', 'ejs') to tell Express to use EJS templates.

The res.render method loads the EJS file and sends the HTML to the browser.

Examples
This line sets EJS as the template engine for your Express app.
Express
app.set('view engine', 'ejs');
This sends the index.ejs file to the browser and passes a variable user with value 'Alice'.
Express
res.render('index', { user: 'Alice' });
Put your EJS files inside a views folder by default.
Express
// Folder structure:
// views/
//   index.ejs
//   partials/
//     header.ejs
Sample Program

This Express app uses EJS to render a simple page. The title variable is shown in the page title and heading.

Express
const express = require('express');
const app = express();

app.set('view engine', 'ejs');

app.get('/', (req, res) => {
  res.render('index', { title: 'Welcome to EJS' });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

// index.ejs file content:
// <html>
// <head><title><%= title %></title></head>
// <body>
//   <h1><%= title %></h1>
//   <p>This page is rendered using EJS template.</p>
// </body>
// </html>
OutputSuccess
Important Notes

Make sure to install EJS with npm install ejs before running your app.

Keep your EJS files in the views folder unless you change the default path.

You can pass many variables to your EJS templates using the object in res.render.

Summary

EJS lets you create dynamic HTML pages easily with Express.

Set EJS as the view engine using app.set('view engine', 'ejs').

Use res.render to send EJS templates with data to the browser.