Conditionals
A conditional chooses which markup to output. Pug has if, else if and else, their opposite unless, and case for choosing among several values. You do not need the parentheses and braces of JavaScript: indentation decides what gets output.
if and else
Let's show on the home page whether the café is open. In src/index.pug:
- const isOpen = true
if isOpen
p.status We are open, come in!
else
p.status Closed right now.After if comes a JavaScript expression, and below it, indented, the markup for the "yes" case. The variable is true, so the first line is output:
<p class="status">We are open, come in!</p>Change the value to false, rebuild the page and you will see "Closed right now."
else if
Several conditions are checked in order, and the first true one wins:
- const hour = 21
if hour < 8
p Still closed, we open at 8:00.
else if hour < 20
p Open until 20:00.
else
p That's all for today, see you tomorrow.21 is not less than 8 or 20, so the else branch ran:
<p>That's all for today, see you tomorrow.</p>unless
unless means "if not". The order button appears only if the drink is not sold out:
- const soldOut = false
unless soldOut
button Orderunless soldOut means the same as if !soldOut but reads more easily:
<button>Order</button>case
When one variable is compared with several values, case is handier. Opening hours depend on the day of the week:
- const day = "sunday"
case day
when "saturday"
when "sunday"
p Weekends: 10:00 to 18:00.
default
p Weekdays: 8:00 to 20:00.A when with no markup under it falls through to the next when, so Saturday and Sunday give the same result. default runs when no value matched:
<p>Weekends: 10:00 to 18:00.</p>A condition in an attribute
For a single attribute you do not need a separate if; the ternary operator is enough:
- const soldOut = true
li(class=soldOut ? "sold-out" : undefined) Hot chocolateWhen an attribute value is undefined, Pug leaves the attribute out. Here the class was added:
<li class="sold-out">Hot chocolate</li>Common mistake
An else indented differently from its if:
if isOpen
p Open.
else
p Closed.Pug treats else as nested inside if and stops the build with the error 'unexpected token "else"'. Put else and else if exactly under their if.