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