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
- Installation & Setup
- File Structure
- Creating Layouts with Pug
- Building the Homepage
- Creating Blog Posts
- Bonus: Dynamic Blog
Installation & Setup
Installing Dependencies
Run the following commands:
npm init -y
npm install express pug
File Structure
Your directory should look like this:
/blog-app/
|-- views/
| |-- layout.pug
| |-- index.pug
| |-- post.pug
|-- app.js
|-- package.json
Creating Layouts with Pug
layout.pug
doctype html
html
head
block title
title Blog - Default Title
body
block content
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
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
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');
});
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)
useful!