test-blog-theme3.online

open
close

Ryan Butter In a Lordly Dish

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

two black computer monitors on black table

Introduction to Pug

Pug, formerly known as Jade, is a high-performance template engine heavily influenced by Haml. It simplifies the process of writing HTML and is widely used in web development due to its concise syntax and powerful features. In this tutorial, we will walk through the steps of setting up and using Pug to create dynamic web pages.

Step 1: Installation

The first step in using Pug is to install it on your system. If you have Node.js installed, you can easily install Pug using npm (Node Package Manager). Open your terminal and run the following command:

npm install pug

This command will install Pug globally on your system, making it accessible from anywhere.

Step 2: Setting Up Your Project

Once Pug is installed, the next step is to set up your project directory. Create a new directory for your project and navigate into it. Inside the project directory, initialize a new Node.js project by running:

npm init -y

This command will generate a package.json file in your project directory, which will manage your project’s dependencies. Next, create a folder named views where you will store your Pug templates.

Step 3: Writing Your First Pug Template

With everything set up, it’s time to write your first Pug template. Inside the views folder, create a new file named index.pug. Open this file and add the following code:

html
  head
    title My First Pug Template
  body
    h1 Hello, Pug!

This simple template creates an HTML document with a title and a heading. Notice how Pug’s indentation-based syntax makes it easy to read and write.

Step 4: Rendering Pug Templates

To render your Pug templates, you need to set up a server. We will use Express.js, a popular Node.js framework, to handle this. First, install Express by running:

npm install express

Next, create a new file named app.js in your project directory and add the following code:

const express = require('express');
const app = express();
const path = require('path');
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));
app.get('/', (req, res) => {
  res.render('index');
});
app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

This code sets up an Express server, configures it to use Pug as the template engine, and renders the index.pug template when the root URL is accessed. Start the server by running:

node app.js

Open your web browser and navigate to http://localhost:3000 to see your Pug template in action.

Conclusion

Congratulations! You have successfully set up and rendered your first Pug template. Pug’s clean and minimalistic syntax makes it an excellent choice for web development. As you continue to explore Pug, you will discover many more features that can help you build dynamic and efficient web applications.

RELATED POSTS

View all

view all