ExpressIntermediate
Express Template Engines (EJS)
EJS install, res.render, dynamic pages — server-side rendering বাংলায়।
9টি অংশবাংলা ভাষায়
Template engine দিয়ে dynamic HTML pages render করা যায়। Express-এর জনপ্রিয় template engine হলো EJS (Embedded JavaScript), Pug, Handlebars।
EJS Setup
npm install ejsconst express = require("express");
const path = require("node:path");
const app = express();
// view engine set
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
// route render
app.get("/", (req, res) => {
res.render("index", {
title: "হোম",
user: { name: "রহিম" },
});
});views/index.ejshtml
html
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1>Welcome, <%= user.name %></h1>
<!-- loop -->
<ul>
<% for (const item of items) { %>
<li><%= item %></li>
<% } %>
</ul>
<!-- conditional -->
<% if (user.isAdmin) { %>
<p>Admin প্যানেল</p>
<% } %>
</body>
</html>Layouts (Partials)
views/partials/header.ejshtml
html
<nav>
<a href="/">হোম</a>
<a href="/about">সম্পর্কে</a>
<a href="/contact">যোগাযোগ</a>
</nav>views/dashboard.ejshtml
html
<body>
<!-- partial include -->
<%- include("partials/header") %>
<main>
<h1>Dashboard</h1>
<p>Welcome, <%= user.name %></p>
</main>
</body>EJS vs React
আপনি যদি front-end-এ React/Next.js ব্যবহার করেন, template engine-এর প্রয়োজন নাও হতে পারে — API-ঠিক backend থাকবে। EJS ছোট server-rendered pages-এ ব্যবহৃত হয়।
শেষ প্যারায় নিজে practice করুন — কোড কপি করে নিজের এডিটরে চালিয়ে দেখুন।