Introduction
A template engine helps you create HTML pages by mixing static content with dynamic data easily.
A template engine helps you create HTML pages by mixing static content with dynamic data easily.
res.render('templateName', { key: value, ... });res.render('home', { title: 'Welcome', user: 'Alice' });
res.render('profile', { age: 30, city: 'Paris' });
This Express app uses EJS as the template engine. When you visit the homepage, it sends the message 'Hello, friend!' to the 'index' template, which shows it inside an <h1> tag.
import express from 'express'; import path from 'path'; const app = express(); // Set EJS as the template engine app.set('view engine', 'ejs'); app.set('views', path.join(process.cwd(), 'views')); app.get('/', (req, res) => { res.render('index', { message: 'Hello, friend!' }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); }); // views/index.ejs content: // <html> // <head><title>Home</title></head> // <body> // <h1><%= message %></h1> // </body> // </html>
Make sure to install the template engine package (like ejs) with npm before using it.
Templates help keep your HTML clean and easy to update without changing server code.
Template engines mix HTML with data to create dynamic pages.
Use res.render() in Express to send data to templates.
Templates keep your design and code separate for easier maintenance.
<h1>Hello, <%= name %></h1> and res.render('greet', { name: 'Sam' }) is called?<%= name %> to insert the value of 'name'.<%= name %>.app.get('/hello', (req, res) => {
res.render('hello', name: 'Alex');
});Pass the test and this pattern moves unknown