Getting started
Basic tags
doctype html
html
head
title My Page
body
h1 Hello World
No closing tags. Nesting via indentation.
Doctype
doctype html
doctype xml
doctype transitional
Block expansion
a: img(src="logo.png")
ul: li: a(href="#") Link
Attributes
Class & ID
.content
#main
a.btn.primary#submit
Div is default if omitted.
Attributes
a(href="//google.com") Google
input(type="text" name="user" required)
Boolean
input(type="checkbox" checked)
input(type="checkbox" checked=false)
Style/Class objects
a(style={color: 'red'})
a(class=['foo', 'bar'])
a(class={active: isActive})
Text & code
Piped text
p
| Line one
| Line two
Block text
script.
console.log('hello')
Buffered code (=)
p= user.name
p= 'Escaped: <html>'
Unescaped (!=)
p!= '<strong>Raw HTML</strong>'
⚠️ XSS risk!
Interpolation
p Hello #{name}
p Raw: !{htmlContent}
p Inline #[strong tag]
Conditionals
If/else
if user.admin
p Admin
else if user.guest
p Guest
else
p User
Unless
unless user.isAnonymous
p Logged in
Iteration
Each
each val in [1, 2, 3]
li= val
each val, i in items
li= i + ': ' + val
each val in items
li= val
else
li No items
While
- var n = 0
while n < 4
li= n++
Mixins
Basic
mixin list
ul
li foo
li bar
+list
With arguments
mixin pet(name)
li.pet= name
+pet('cat')
+pet('dog')
With block
mixin card(title)
.card
h2= title
if block
block
+card('Title')
p Content
With attributes
mixin link(href, name)
a(class!=attributes.class href=href)= name
+link('/foo', 'Foo')(class="btn")
Inheritance
Layout
//- layout.pug
html
head
block head
body
block content
Page
extends layout.pug
block head
title My Page
block content
h1 Hello
Append/prepend
extends layout.pug
append head
script(src="/app.js")
Includes
Files
include includes/head.pug
include includes/nav.pug
Plain text
style
include style.css
script
include app.js
Comments
Buffered
// Visible in HTML
Unbuffered
//- Hidden from output
Gotchas
Pitfalls
| Issue | Fix |
|---|---|
| Indent errors | Use 2 spaces |
| Old interpolation | Use '/'+url not /#{url} |
| XSS | Avoid != with user input |
Also see
- Pug Docs (pugjs.org)
- Pug GitHub (github.com)