pass data ino pug nodejs

// 1. Require necessary modules
const express = require('express');
const path = require('path');

// 2. Create an Express application
const app = express();

// 3. Set the view engine to Pug
app.set('view engine', 'pug');

// 4. Set the views directory
app.set('views', path.join(__dirname, 'views'));

// 5. Define a route to render the Pug template
app.get('/', (req, res) => {
  // 6. Define data to be passed to the Pug template
  const data = {
    title: 'Passing Data to Pug in Node.js',
    message: 'Hello, this is a message from the server!',
  };

  // 7. Render the Pug template with the provided data
  res.render('index', data);
});

// 8. Start the Express server
const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

In the above code:

  1. Import the necessary modules (express for building the web application and path for working with file and directory paths).
  2. Create an Express application.
  3. Set the view engine to Pug using app.set('view engine', 'pug').
  4. Set the views directory using app.set('views', path.join(__dirname, 'views')), assuming your Pug templates are in a 'views' directory.
  5. Define a route for the root URL ('/') that renders a Pug template.
  6. Create a data object (data) with properties that you want to pass to the Pug template.
  7. Use res.render('index', data) to render the Pug template named 'index' with the provided data.
  8. Start the Express server on a specified port (default is 3000) and log a message to the console when the server is running.