test-blog-theme3.online

open
close

Molly Everything is Illuminated

June 19, 2024 | by test-blog-theme3.online

pug covered with blanket on bedspread

Introduction to Pug

Pug, formerly known as Jade, is a popular templating engine for Node.js and other web applications. It allows developers to write cleaner and more readable HTML by using a simplified syntax. This tutorial will provide a step-by-step guide on how to use Pug, covering installation, basic syntax, and practical examples.

Installing Pug

Before you can start using Pug, you need to install it. Ensure that you have Node.js and npm installed on your system. Open your terminal and run the following command:

npm install pug

This command will install Pug and make it available for use in your project.

Basic Syntax of Pug

Pug simplifies HTML writing by eliminating the need for closing tags and reducing the amount of code you have to write. Here’s a basic example to illustrate the syntax:

doctype html
html
head
title Pug Tutorial
body
h1 Welcome to Pug
p This is an example of Pug syntax.

This Pug code will be compiled into the following HTML:

<!DOCTYPE html>
<html>
<head>
<title>Pug Tutorial</title>
</head>
<body>
<h1>Welcome to Pug</h1>
<p>This is an example of Pug syntax.</p>
</body>
</html>

Using Pug with Express

To use Pug with an Express application, first set up a basic Express server. Install Express by running:

npm install express

Next, set up your server to use Pug as its view engine:

const express = require('express');
const app = express();
app.set('view engine', 'pug');
app.get('/', (req, res) => {
res.render('index', { title: 'Pug Tutorial', message: 'Welcome to Pug with Express' });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});

Create a views directory and add an index.pug file:

doctype html
html
head
title= title
body
h1= message

When you visit http://localhost:3000, you should see the message rendered by Pug.

Conclusion

Pug is a powerful templating engine that simplifies the process of writing HTML. By following this step-by-step guide, you should be able to install Pug, understand its basic syntax, and integrate it with an Express application. Pug’s simplicity and efficiency make it a valuable tool for any web developer.

RELATED POSTS

View all

view all