Steps to Create NodeJS App and Installing Module
Step 1: Create a NodeJS application using the following command:
npm init
Step 2: Install required Dependencies:
npm i pug express
The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.18.2",
"pug": "^3.0.2"
}
Example: The Below example is demonstrating the use of Pug Elements:
//File path: views/index.pug
html
head
// Set the title of the HTML page
title Pug Example
// Internal CSS styles for the page
style.
h1 {
color: green;
}
.heading {
font-style: italic;
}
body
// Display the main heading of the page
h1 w3wiki | Pug Elements
// Display a subheading
h4.heading This h4 with heading class
// Display a Ordered List
ol
li first
li second
li third
// Input Box
input(
type='text'
name='name'
placeholder='Enter Name'
)
button(type='submit') Submit
//File path: /index.js (root)
// Import required modules
const express = require('express');
const path = require('path');
// Create an Express application
const app = express();
// Define the port for the server to listen on
const port = 3000;
// Set Pug as the view engine
app.set('view engine', 'pug');
// Set the views directory to 'views' in the current directory
app.set('views', path.join(__dirname, 'views'));
// Define a route to render the Pug template
// when the root path is accessed
app.get('/', (req, res) => {
// Render the Pug template named 'index'
res.render('index');
});
// Start the server and listen on the specified port
app.listen(port, () => {
// Display a message when the server starts successfully
console.log(`Server is running at http://localhost:${port}`);
});
To run the application use the following command:
node index.js
Output: Now go to http://localhost:3000 in your browser:
Elements in Pug View Engine
Pug is a template engine that works with JavaScript libraries and frameworks. It simplifies the process of writing HTML by reducing traditional HTML syntax. It uses indentation to represent HTML structure. By using Pug you can reuse the HTML code.
In this article, we will learn about Pug Elements with its syntax and example.