Template Engines

Express can render dynamic HTML pages using template engines like EJS, Pug, or Handlebars.

a. Installing a Template Engine

For EJS, install it with npm:

npm install ejs

Set up EJS in app.js:

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

Create a views directory and add an index.ejs file:

<!DOCTYPE html>
<html>
<head>
  <title><%= title %></title>
</head>
<body>
  <h1>Hello, <%= name %>!</h1>
</body>
</html>

Render the template in your route:

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

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *