Template engine in express JS
What is a Template Engine?
- A template engine lets you generate dynamic HTML using server-side data.
- Helps merge backend data with frontend templates (like variables in HTML).
Popular Template Engines
- EJS (Embedded JavaScript) ✅
- Pug (formerly Jade)
- Handlebars
How to Install EJS
npm i ejs
EJS File Structure
project/
│
├── views/
│ └── home.ejs
├── public/
│ └── style.css
└── index.js
Note: EJS automatically looks inside the views/
folder
Example: home.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Home Page</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Name <%= name %></h1>
<h2>Yt Channel: <%= ytChannel %></h2>
<h2>Age : <%= age %></h2>
</body>
</html>
-
<%= ... %>
is used to embed JavaScript values in HTML
index.js
import express from "express";
const app = express();
app.set("view engine", "ejs");
app.get("/", (req, resp) => {
resp.render("home", {
name: "Anil Sidhu",
ytChannel: "Code Step By Step",
age: 29,
});
});
app.listen(3200);
app.set("view engine", "ejs");
tells Express to use EJS
resp.render("home", {...})
sends data to the EJS file
Output at http://localhost:3200/
:
Name Anil Sidhu
Yt Channel: Code Step By Step
Age : 29