jstevens13
jstevens13

Reputation: 1245

Jade conditional (if/else) to add class to div inline

Is there a way to do this inline in a jade template?

if(typeof fromEdit != 'undefined')
   div#demo.collapse.in
else
   div#demo.collapse

Would like to do this conditional check "inline" and the result would add the .in to the end of the div if fromEdit exists.

Upvotes: 82

Views: 56817

Answers (6)

Parth Developer
Parth Developer

Reputation: 1857

Multiple conditional classes

p(class={"true-class": isTrue, "false-class": !isTrue})

Upvotes: 1

korywka
korywka

Reputation: 7653

With pug 2 you can use this syntax:

div#demo(class="collapse", class={"in": typeof fromEdit !== 'undefined'}) Home page

more here: https://pugjs.org/language/attributes.html

Upvotes: 3

Arkanoid
Arkanoid

Reputation: 1195

If you don't want the class attribute to be added when there is no value, you can assign it undefined instead of an empty string. Here is the previous example, slightly modified:

div#demo.collapse(class=typeof fromEdit === "undefined" ? undefined : "in")

Update: Also, if you are using pug, you can now add as many class= declarations as you want with different conditions and they'll get concatenated in the resulting class attribute. e.g.:

#demo.collapse(class=cond1 && 'class1' class=cond2 && 'class2')

Upvotes: 83

Matthew Sundberg
Matthew Sundberg

Reputation: 320

Though an old question, I find that the following works since Pug includes object existence detection built in:

div#demo.collapse(class=fromEdit? 'in':undefined)

If it's not obvious, this checks if fromEdit exists and if it does enters in as the class, otherwise leaving the class blank.

Upvotes: 2

infografnet
infografnet

Reputation: 4005

As documented at http://jade-lang.com/reference/attributes/:

The class attribute [...] It can also be an object mapping class names to true or false values, which is useful for applying conditional classes

the task can be also done by the following:

div#demo.collapse(class={ in: typeof fromEdit != 'undefined' })

Although it doesn't work here http://naltatis.github.com/jade-syntax-docs/ (I think they need to update something), but it works with [email protected] .

Upvotes: 6

Dogbert
Dogbert

Reputation: 222118

This works:

div#demo.collapse(class=typeof fromEdit === "undefined" ? "" : "in")

Try it out here.

Upvotes: 118

Related Questions