test-blog-theme3.online

open
close

Janine LaCroix Carrion Comfort

August 28, 2024 | by test-blog-theme3.online

pug covered with blanket on bedspread

Introduction to Pug

Pug, previously known as Jade, is a high-performance template engine heavily used in server-side programming languages such as Node.js. It enables developers to write cleaner, more readable HTML code with simplified syntax and extensive support for dynamic content. This tutorial will walk you through the basic steps of getting started with Pug.

Step 1: Installation

Firstly, you need to install Pug using npm, Node.js’ package manager. Open your terminal and run the following command:

““ $ npm install pug “`

This will install the Pug package in your project directory, making it available globally within your project.

Step 2: Basic Setup

After installation, you need to set up your project to make use of Pug templates. Create a new JavaScript file (for instance, `app.js`) in your project directory and require Pug as follows:

““ const pug = require(‘pug’); ““

You can now compile a Pug file to HTML. For instance, if you have a Pug file named `index.pug`, you can use the following script to compile it:

““ let html = pug.renderFile(‘index.pug’);console.log(html); ““

Step 3: Creating Pug Templates

Now comes the part where you write your Pug templates. Create a file named `index.pug` in your project directory and add the following content:

““doctype html html head title My Pug Template body h1 Hello World p Welcome to your first Pug tutorial! ““

This simple Pug file will compile into a complete HTML document with a heading and a paragraph.

Step 4: Integrating Pug with Express

Express is a popular web framework for Node.js. Integrating Pug with Express allows you to render Pug templates dynamically. Set up an Express server by adding the following code in your `app.js`:

““ const express = require(‘express’); const app = express(); app.set(‘view engine’, ‘pug’); app.get(‘/’, (req, res) => { res.render(‘index’); }); app.listen(3000, () => { console.log(‘Server is running on port 3000’); }); ““

This code configures Express to use Pug as the template engine and renders the `index.pug` template when the root URL is accessed.

Conclusion

Following these steps, you have set up a basic Pug template, integrated it with an Express application, and successfully rendered dynamic content. Mastering Pug allows you to write more organized and readable code, making your development process more efficient.

RELATED POSTS

View all

view all