Pug’s #
Pug, formerly known as Jade, is a concise and expressive template engine for Node.js and browsers. It uses a simplified syntax with indentation-based markup, making it easy to read and write. Below is a basic overview of using Pug in a Node.js application:
Installation: #
Install Pug using npm:
npm install pug
Setting Up Pug in Express: #
If you are using Express, set up Pug as the view engine:
const express = require('express');
const app = express();
app.set('view engine', 'pug');
app.set('views', __dirname + '/views');
app.get('/', (req, res) => {
res.render('index', { title: 'Pug Example', message: 'Hello, Pug!' });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Creating a Pug Template: #
Create a Pug template file (e.g., views/index.pug):
doctype html
html(lang="en")
head
meta(charset="UTF-8")
meta(name="viewport", content="width=device-width, initial-scale=1.0")
title= title
body
h1= message
The title and message variables are replaced with the values passed during rendering.
Passing Data to Pug Template: #
In your Express route, use res.render to pass data to the Pug template:
app.get('/', (req, res) => {
res.render('index', { title: 'Pug Example', message: 'Hello, Pug!' });
});
Conditional Statements in Pug: #
Use Pug syntax for conditionals:
if user
p Welcome, #{user.username}!
else
p Please log in
Iterating Over Arrays in Pug: #
Use Pug syntax for loops:
ul
each user in users
li= user.username
Including Partials in Pug: #
Create Pug partials and include them in other templates:
// views/header.pug
header
h1= title
// views/index.pug
include header
body
p= message
Mixins in Pug: #
Define and use mixins for reusable components:
mixin userCard(user)
.user-card
h2= user.username
p= user.email
each user in users
+userCard(user)
Custom Filters in Pug: #
Create custom filters for additional functionality:
:uppercase
p Hello, World!
Middleware for Pug: #
Use Pug as middleware to render dynamic content in responses:
const express = require('express');
const app = express();
app.set('view engine', 'pug');
app.use((req, res, next) => {
res.locals.username = 'John';
next();
});
app.get('/', (req, res) => {
res.render('index');
});
Pug’s simplicity, readability, and expressiveness make it a popular choice for templating in Node.js applications. It offers features like conditionals, loops, mixins, and filters that contribute to creating modular and maintainable views. Whether used with Express for server-side rendering or in the context of front-end development, Pug provides an efficient way to generate HTML content with a clean and concise syntax.