Share
Explore

PUG HTML Templating Language

To teach the use of a templating engine like Pug (formerly known as Jade) in a Node.js application, we'll modify the previous e-commerce application to use Pug templates for rendering the frontend. Pug is a concise and powerful templating engine that allows us to write HTML code in a more structured and efficient way. Here's how you can update the previous lab to incorporate Pug as the template engine:
Step 1: Set Up the Project
1.1. Create a new folder for the project, navigate into it, and run npm init to initialize the project.
1.2. Install required dependencies:
Express.js: Web framework for Node.js
MongoDB driver: To connect to the MongoDB database
Body-parser: To parse incoming request bodies
Pug: The templating engine
bashCopy code
npm install express mongodb body-parser pug

Step 2: Update Backend - Server and MongoDB Connection
2.1. Create an app.js file (or whatever name you prefer) in your project's root directory. This will be your main backend file.
2.2. Import the required modules and set up the basic Express server.
javascriptCopy code
// app.js

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000; // You can use any port number you prefer

// Body parser middleware
app.use(bodyParser.json());

// MongoDB connection setup (You'll need to replace <YOUR_MONGO_CONNECTION_STRING> with your actual MongoDB connection string)
const MongoClient = require('mongodb').MongoClient;
const mongoURI = '<YOUR_MONGO_CONNECTION_STRING>';

// Connect to MongoDB
MongoClient.connect(mongoURI, { useUnifiedTopology: true }, (err, client) => {
if (err) {
console.log('Error connecting to MongoDB:', err);
return;
}
console.log('Connected to MongoDB!');
const db = client.db('ecommerce'); // Replace 'ecommerce' with your desired database name

// Set the 'views' directory as the location for Pug templates
app.set('views', './views');
app.set('view engine', 'pug');

// Start the server after successful database connection
app.listen(port, () => {
console.log(`Server started on http://localhost:${port}`);
});

// Add your MongoDB-related code here (e.g., creating collections, inserting data, etc.)
// We'll add this code in Step 3.
});

Step 3: Set Up MongoDB and Create Sample Documents
3.1. Inside the MongoDB connection block in app.js, create a MongoDB collection named 'products', and insert some sample documents. We'll keep this code unchanged from the previous version.
Step 4: Set Up Frontend - Pug Templates
4.1. Create a new directory named views in your project's root directory. This is where your Pug templates will be stored.
4.2. Create a Pug template named index.pug inside the views directory. This will be your frontend template.
pugCopy code
// views/index.pug

doctype html
html
head
title E-commerce Website
body
h1 Welcome to Our E-commerce Website

h2 Products
ul#product-list
//- Product items will be added dynamically using JavaScript

h2 Add New Product
form#add-product-form
label(for='name') Product Name:
input#name(type='text', name='name', required)
br
label(for='price') Product Price:
input#price(type='number', name='price', step='0.01', required)
br
label(for='category') Product Category:
input#category(type='text', name='category', required)
br
button(type='submit') Add Product

script(src='frontend.js')

Step 5: Set Up Frontend - JavaScript to Connect to Backend (API Endpoints)
5.1. We don't need to change anything in the frontend JavaScript code (frontend.js) because it interacts with the backend through the same API endpoints as before.
Step 6: Backend - API Routes to Handle CRUD Operations
6.1. Add the following API routes to handle CRUD operations for products in your app.js file. These remain unchanged from the previous version.
javascriptCopy code
// app.js

// ...

// API endpoint to get all products
app.get('/api/products', (req, res) => {
// ... (same code as before)
});

// API endpoint to add a new product
app.post('/api/products', (req, res) => {
// ... (same code as before)
});

With these modifications, your Node.js application now uses the Pug template engine to render the frontend instead of plain HTML. Pug allows you to write cleaner, more readable templates with less boilerplate code, making it easier to manage and maintain the frontend of your application.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.