Getting Started with Pug and Express for Your Web App
Building web apps with Node.js and Express is like making a Lego masterpiece. To turn it into a dynamic, interactive canvas, you can use a templating engine. One of the coolest ones out there is Pug, previously known as Jade. Let’s dive into setting up and using Pug to make your web pages come to life.
Kicking Off the Project
First things first—let’s set up your project. Create a new directory for it, and hop into that folder. Once you’re in, kick-start a new Node.js project by running:
npm init -y
This nifty little command creates a package.json
file, which is like your project’s little black book for managing all of its dependencies.
Getting Your Essentials
Next up, you need to install Express and Pug. Just run:
npm install express pug
Bam! You now have Express and Pug in your toolkit.
Setting the Stage
Create a new file called app.js
in your project directory—think of this as the control center for your Express app. Also, set up a views
folder where all your Pug templates will live.
Your project should look something like this:
project/
├── app.js
├── package.json
└── views/
└── index.pug
Getting Express to Play Nice with Pug
Time to configure Express to use Pug. Here’s how to set it up in your app.js
file:
const express = require('express');
const app = express();
const port = 3000;
app.set('view engine', 'pug');
app.set('views', './views');
app.get('/', (req, res) => {
res.render('index', { title: 'Welcome to Pug', message: 'Hello from Pug!' });
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
In this code, you’re telling Express to use Pug as the templating engine and pointing it to your views
directory for templates.
Crafting Pug Templates
Let’s whip up a simple Pug template. Open index.pug
in your views
folder and add this:
doctype html
html
head
title= title
body
h1= message
p Welcome to our website!
In this template, title
and message
are placeholders for real values that will be filled in when the template is rendered. The beauty of Pug lies in its clean and indentation-based syntax.
Firing Up the Server
Ready? Time to hit the road. Start your app by running:
node app.js
Your server is now up and running. Pop open your web browser and navigate to http://localhost:3000
. You should see your page with the title and message you set earlier.
Power of Pug Templates
Pug isn’t just about static content; it rocks some cool features like template inheritance. This lets you create a base layout that other pages can extend. Here’s how.
First, make a layout.pug
in your views
folder:
doctype html
html
head
meta(charset='UTF-8')
meta(name='viewport' content='width=device-width, initial-scale=1.0')
title #{title}
body
div#root
block content
Next, create an index.pug
that extends this layout:
extends layout
block content
h1= message
p Welcome to our website!
Here, index.pug
is using layout.pug
as a base and filling in the content block with its own bits.
Sprucing Things Up with CSS
Wanna add some flair? Let’s throw in some styling. Make a public
directory in your project root and create a style.css
file inside it:
/* public/style.css */
body {
background-color: aqua;
}
Then update layout.pug
to link this stylesheet:
doctype html
html
head
meta(charset='UTF-8')
meta(name='viewport' content='width=device-width, initial-scale=1.0')
title #{title}
link(rel='stylesheet' href='/style.css')
body
div#root
block content
Don’t forget to serve your public
directory by adding this to your app.js
:
app.use(express.static('public'));
Now your styles will be applied, and you’ll get that nice aqua background.
Rolling with Dynamic Data
Pug also makes it super easy to render dynamic data. Here’s how to pass data from your route handler to your Pug template.
Update your route handler in app.js
like this:
app.get('/', (req, res) => {
const userData = { name: 'John Doe', age: 30 };
res.render('index', { title: 'User Profile', message: 'Hello, John!', userData });
});
Then, tweak your index.pug
to display this dynamic data:
doctype html
html
head
title= title
body
h1= message
p User Name: #{userData.name}
p User Age: #{userData.age}
Voilà! Your page will now dynamically generate content based on the data passed from your server.
Wrapping It Up
Using Pug with Express turns the task of generating dynamic HTML content into a smooth and enjoyable ride. Its clean syntax and powerful features, like template inheritance, make it a go-to tool for creating maintainable web applications. Whether you’re working on a simple project or embarking on a complex app, Pug can simplify your workflow and elevate your coding game.
There you have it—a full run-through of building dynamic web pages with Pug and Express. Happy coding!