How to Use Pug
Pug is a powerful template engine that simplifies HTML writing with its concise and readable syntax. Here's how to get started.
Installation
To install Pug, you'll need Node.js and npm. Run the following command:
npm install pug If you want to use Pug as a command-line tool:
npm install -g pug-cliBasic Syntax
Tags
HTML tags are represented without angle brackets:
html
head
title My Site
body
h1 Hello World
p This is a paragraphAttributes
Attributes are enclosed in parentheses:
a(href="https://pugjs.org", target="_blank") Pug Website
input(type="text", placeholder="Enter your name")
meta(charset="utf-8")Classes and IDs
CSS classes and IDs use shortcuts:
// Classes
.container
.row
.col-md-6.text-center Hello
// IDs
#header Header
#footer Footer
// Combined
div#content.main-content ContentText Content
Text can be put after the tag or indented:
// Inline text
p This is a paragraph
// Block text
p
| This is a paragraph
| with multiple lines
| of textAdvanced Features
Variables and Interpolation
// Define variables at the top
- var name = "John"
- var age = 30
p Hello, my name is #{name}
p I am #{age} years oldConditionals
- var isLoggedIn = true
if isLoggedIn
p Welcome back!
else
p Please log in.Loops
- var items = ["Apple", "Banana", "Orange"]
ul
each item in items
li= itemMixins
mixin card(title, content)
.card
.card-header= title
.card-body= content
+card("Hello", "This is a card")
+card("Another Card", "More content")Integration Examples
Using Pug with Express
// app.js
const express = require('express');
const app = express();
// Set up Pug as the template engine
app.set('view engine', 'pug');
app.set('views', './views');
app.get('/', (req, res) => {
res.render('index', {
title: 'Home Page',
message: 'Welcome to my website!'
});
});
app.listen(3000, () => {
console.log('Server running on port 3000');
}); And the corresponding Pug template:
// views/index.pug
doctype html
html
head
title= title
body
h1= message
p This is rendered using Pug!