Add multiple classes in pug

ยท

3 min read

Pug, formerly known as Jade, is a template engine thas uses a JavaScript render. Sometimes we have to add a class conditionally based on a variable, here I go with some tricky solutions I found.

One condition to check

The easiest way to check a class in pug is using the ternary operator

- var cond1 = true
.c-component(class=cond1 ? 'cond1-TRUE' : 'cond1-FALSE' )

HTML output

<div class="c-component cond1-true"></div>

But there are other two ways to write the same exact condition in pug:

- var cond1 = true

//- (1)
.c-component(class={'cond1-true': cond1 === true})

//- (2)
.c-component(class={cond1True: cond1 === true})

Important

๐Ÿงจ !important (1) kebab-case class cond1-true must be wrapped in quotes (2) camelCase class cond1True can skip wrapper quotes

HTML output

<div class="c-component cond1-true"></div>
<div class="c-component cond1True"></div>

More than one condition to check

If we have to check two condintions, we can go also in this case with the ternary operator to choose which classes we want.

We can write the conditionals in three ways:

  1. using two class attributes separated by space
(class=cond1 ? 'cond1-TRUE' : 'cond1-FALSE' class=cond2 ? 'cond2-TRUE' : 'cond2-FALSE')
  1. using two class attributes separated by comma
(class=cond1 ? 'cond1-TRUE' : 'cond1-FALSE', class=cond2 ? 'cond2-TRUE' : 'cond2-FALSE')
  1. using two class attributes, one for each parentesis
    (class=cond1 ? 'cond1-TRUE' : 'cond1-FALSE')(class=cond2 ? 'cond2-TRUE' : 'cond2-FALSE')
    

All three:

pug

- var cond1 = true
- var cond2 = false

.c-component(class=cond1 ? 'cond1-TRUE' : 'cond1-FALSE' class=cond2 ? 'cond2-TRUE' : 'cond2-FALSE')

.c-component(class=cond1 ? 'cond1-TRUE' : 'cond1-FALSE', class=cond2 ? 'cond2-TRUE' : 'cond2-FALSE')

.c-component(class=cond1 ? 'cond1-TRUE' : 'cond1-FALSE')(class=cond2 ? 'cond2-TRUE' : 'cond2-FALSE')

HTML output

<div class="c-component cond1-TRUE cond2-FALSE"></div>

<div class="c-component cond1-TRUE cond2-FALSE"></div>

<div class="c-component cond1-TRUE cond2-FALSE"></div>

If we have a ternary option with the second operand empty, we could simplify the pug syntax:

- var cond1 = true
- var cond2 = false

.c-component(class=cond1 && 'cond1-TRUE' class=cond2 && 'cond2-TRUE')
//- or more explicit
.c-component(class=cond1 ? 'cond1-TRUE' : '' class=cond2 ? 'cond2-TRUE' : '')

HTML output

<div class="c-component cond1-TRUE"></div>

๐Ÿ–ฅ Codepen example.

๐Ÿ“š More info