DEV Community

Lord Neic
Lord Neic

Posted on

Building a Blog with Pug and Node.js: A Comprehensive Guide

Introduction

In this tutorial, we'll explore how to build a simple blog using Pug as the templating engine and Node.js with Express as the backend. This guide is well-suited for developers interested in full-stack development and who are particularly experienced with backend systems.

Table of Contents

  1. Installation & Setup
  2. File Structure
  3. Creating Layouts with Pug
  4. Building the Homepage
  5. Creating Blog Posts
  6. Bonus: Dynamic Blog

Installation & Setup

Installing Dependencies

Run the following commands:

npm init -y
npm install express pug
Enter fullscreen mode Exit fullscreen mode

File Structure

Your directory should look like this:

/blog-app/
|-- views/
|   |-- layout.pug
|   |-- index.pug
|   |-- post.pug
|-- app.js
|-- package.json
Enter fullscreen mode Exit fullscreen mode

Creating Layouts with Pug

layout.pug

doctype html
html
  head
    block title
      title Blog - Default Title
  body
    block content
Enter fullscreen mode Exit fullscreen mode

Here, we've used Pug's block features, which allows us to define placeholders for dynamic content.

Building the Homepage

index.pug

extends ./layout.pug

block title
  title Blog - Home

block content
  h1 Welcome to My Blog
  ul
    each post, index in posts
      li
        a(href="/post/" + post.id)= post.title
Enter fullscreen mode Exit fullscreen mode

We use the extends keyword to inherit from layout.pug. The each loop is used to iterate over our posts.

Creating Blog Posts

post.pug

extends ./layout.pug

block title
  title Blog - #{post.title}

block content
  h1= post.title
  p= post.content
Enter fullscreen mode Exit fullscreen mode

We use the #{\} syntax to interpolate variables in Pug. This makes our blog post titles dynamic.

Bonus: Dynamic Blog

app.js

const express = require('express');
const app = express();

app.set('view engine', 'pug');

const posts = [
  { id: 1, title: 'First Post', content: 'This is the first post.' },
  { id: 2, title: 'Second Post', content: 'This is the second post.' },
];

app.get('/', (req, res) => {
  res.render('index', { posts });
});

app.get('/post/:id', (req, res) => {
  const post = posts.find(p => p.id === parseInt(req.params.id));
  res.render('post', { post });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Enter fullscreen mode Exit fullscreen mode

Here, we've used Express to set up our server and routes. We also created a mock posts array to simulate the data that you would typically fetch from a database.

Top comments (1)

Collapse
 
shivams1007 profile image
Shivam Singh

useful!