Express.js Masterclass
The Professional Backend Framework01.Home02.Introduction03.Express vs Native Node04.Express Generator05.Request Object (req)06.Response Object (res)07.Advanced Routing08.URL Params & Query09.Body Parsing10.Template Engines (EJS)11.Serving Static Files12.Middleware Architecture13.Must-Have Middleware14.File Uploads (Multer)15.Custom Error Handling16.Cookies & Sessions17.User Auth (Passport)18.Database Integration19.Data Validation20.Socket.io in Express21.Security & Helmet
Template Engines (EJS)
A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client.
1. Installation & Setup
npm install ejsIn your app.js:
app.set('view engine', 'ejs');
app.set('views', './views'); // Default folder2. Creating a Template (index.ejs)
EJS files use .ejs extension and look exactly like HTML, but with brackets <% %>.
<html>
<body>
<h1>Welcome, <%= userName %>!</h1>
<ul>
<% items.forEach(item => { %>
<li><%= item %></li>
<% }); %>
</ul>
</body>
</html>3. Rendering the View
app.get('/', (req, res) => {
res.render('index', {
userName: 'Pradeep',
items: ['Learn Express', 'Build App', 'Deploy']
});
});Pug vs EJS: EJS uses vanilla HTML/JS syntax, making it easier for many. Pug uses indentation-based syntax which is cleaner but has a steeper learning curve.