Share
Explore

Node.js application that showcases the use of the Pug templating language.

Complete Code Base for this Lab:
This example will render a basic webpage using Pug as the templating engine.
Step 1: Set Up the Project
1.1. Create a new folder for the project and navigate into it.
1.2. Initialize a new Node.js project by running npm init and following the prompts.
1.3. Install required dependencies:
bashCopy code
npm install express pug

Step 2: Create the Backend - Express Server with Pug Templating
2.1. Create an app.js file in your project's root directory.
2.2. Import the required modules and set up the Express server to use Pug as the templating engine.
// app.js

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

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

// Define a route to render the Pug template
app.get('/', (req, res) => {
res.render('index', { title: 'Simple Pug Template' });
});

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

Step 3: Create the Pug Template
3.1. Create a new directory named views in your project's root directory. This is where your Pug template will be stored.
3.2. Create a Pug template named index.pug inside the views directory. This will be the simplest Pug template.

// views/index.pug

doctype html
html
head
title= title
body
h1 Hello, Pug Templating!

Step 4: Run the Application
4.1. Open a terminal and navigate to the project's root directory.
4.2. Run the application using Node.js:
node app.js

4.3. Open your web browser and visit http://localhost:3000. You should see a basic webpage with the text "Hello, Pug Templating!" rendered using Pug.
In this example, we set up a basic Node.js application using Express and the Pug templating engine. The Pug template (index.pug) is a simple HTML file written using Pug's concise syntax.

The res.render() method in the backend renders the Pug template, and we pass the title variable as data to the template.
The value of title is set to "Simple Pug Template," and it gets interpolated into the HTML title element in the rendered page.
This demonstrates the most basic usage of Pug in a Node.js application.


Let's extend the simplest Node.js application lab to showcase ten progressively more detailed examples of adding HTML, forms, CSS, and other frontend web app building patterns using Pug and Express.
Step 1: Set Up the Project
1.1. Create a new folder for the project and navigate into it.
1.2. Initialize a new Node.js project by running npm init and following the prompts.
1.3. Install required dependencies:

npm install express pug

Step 2: Create the Backend - Express Server with Pug Templating
2.1. Create an app.js file in your project's root directory.
2.2. Import the required modules and set up the Express server to use Pug as the templating engine.
javascriptCopy code
// app.js

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

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

// Define a route to render the Pug template
app.get('/', (req, res) => {
res.render('index', { title: 'Simple Pug Template' });
});

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

Step 3: Create the Pug Template
3.1. Create a new directory named views in your project's root directory. This is where your Pug templates will be stored.
3.2. Create a Pug template named index.pug inside the views directory. This will be the simplest Pug template.
pugCopy code
// views/index.pug

doctype html
html
head
title= title
body
h1 Hello, Pug Templating!

Step 4: Run the Application
4.1. Open a terminal and navigate to the project's root directory.
4.2. Run the application using Node.js:
bashCopy code
node app.js

4.3. Open your web browser and visit http://localhost:3000. You should see a basic webpage with the text "Hello, Pug Templating!" rendered using Pug.
Now let's add the progressive examples:
Example 1: Adding a Basic HTML Form
pugCopy code
// views/index.pug

doctype html
html
head
title= title
body
h1 Hello, Pug Templating!

form(action="/submit", method="POST")
label(for="name") Your Name:
input(type="text", name="name", required)
br
button(type="submit") Submit

Example 2: Processing Form Submission
// app.js

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

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

// Body parser middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Define a route for the root URL and render the Pug template
app.get('/', (req, res) => {
res.render('index', { title: 'Simple Pug Template' });
});

// Define a route to render the Pug template with a form
app.get('/form', (req, res) => {
res.render('form', { title: 'Form Example' });
});

// Define a route to handle form submission
app.post('/submit', (req, res) => {
const name = req.body.name;
res.send(`Hello, ${name}! Your form was submitted successfully.`);
});

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

Let's add some interesting uses of jQuery to the index.pug template. We'll use jQuery to enhance the user experience by performing some interactive actions on the form.

To use jQuery, make sure you have included the jQuery library in your project. You can either download it and include it directly in your project or use a CDN (Content Delivery Network). For this example, we'll use a CDN to include jQuery.

Here's the updated index.pug template with some interesting jQuery features:

pug
Copy code
// views/index.pug

doctype html
html
head
title= title
link(rel="stylesheet", href="/styles.css")

// Include jQuery from the CDN
script(src="https://code.jquery.com/jquery-3.6.0.min.js")

// jQuery script for interactive form actions
script.
$(document).ready(function() {
// Hide the submit button initially
$('button[type="submit"]').hide();

// Show the submit button only when the input field is filled
$('input[name="name"]').on('input', function() {
if ($(this).val().trim() !== '') {
$('button[type="submit"]').show();
} else {
$('button[type="submit"]').hide();
}
});

// Show a greeting message upon form submission
$('form').on('submit', function(event) {
event.preventDefault();
const name = $('input[name="name"]').val().trim();
if (name !== '') {
alert('Hello, ' + name + '! Your form was submitted successfully.');
}
});
});

body
h1 Hello, Pug Templating!

form(action="/submit", method="POST")
label(for="name") Your Name:
input(type="text", name="name", required)
br
// The submit button is hidden initially and shown dynamically using jQuery
button(type="submit") Submit

In this updated template, we've added a <script> tag to include jQuery from the CDN. Below that, we've added a <script> block that contains jQuery code.

Hiding and Showing the Submit Button: Initially, the submit button is hidden using jQuery ($('button[type="submit"]').hide();). When the user starts typing in the input field, the submit button is shown ($('button[type="submit"]').show();) only if the input field is not empty.

Greeting Message on Form Submission: When the form is submitted, we prevent the default form submission behavior (event.preventDefault();). Then, we extract the value from the input field (const name = $('input[name="name"]').val().trim();). If the input field is not empty, we show a greeting message using alert().

With these jQuery enhancements, the form becomes more interactive, making the user experience more engaging and enjoyable. Remember to save the changes and restart your Node.js server to see these enhancements in action.

Here's a styles.css file that includes the styles for the red page background and gold large letters, which we will apply to the index.pug template:
cssCopy code
/* styles.css */

body {
background-color: red;
color: gold;
}

h1 {
font-size: 3rem;
}

Save this CSS code in a file named styles.css in the root directory of your project. Make sure that the styles.css file is in the same folder as the index.pug and app.js files.
When you run the Node.js application and access the index page, it will apply the styles from styles.css, giving you a red page background with gold large letters for the heading. Additionally, when you fill out the form and submit it, the background color will change to blue, thanks to the jQuery script we added in the previous step.

Example 3: Adding CSS Styling

// views/index.pug

doctype html
html
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.