81

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.

jstevens13
  • 1,235
  • 3
  • 11
  • 9

6 Answers6

116

This works:

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

Try it out here.

Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • 2
    but you wouldn't even want the element to have a `class` attribute if the condition is false.. – vsync May 13 '13 at 14:37
  • How to do it for object value like a(class=tasks[i].status ? 'btn btn-success' : 'btn btn-dark', href=`/turn/ ${tasks[i]._id}`) Done showing error Cannot read property 'status' of undefined – Pankaj May 07 '19 at 07:46
83

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')
Arkanoid
  • 1,165
  • 8
  • 17
  • What about a case when there are multiple condition must be checked? For example two classes each with its own check? – Alex Shwarc Mar 12 '16 at 12:09
6

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 jade@1.11.0 .

infografnet
  • 3,749
  • 1
  • 35
  • 35
  • This is the way to go now with jade/pug. It allows multiple conditionnal classes, with adding another key to the object. – webdif Aug 05 '16 at 14:56
3

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

korywka
  • 7,537
  • 2
  • 26
  • 48
2

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.

1

Multiple conditional classes

p(class={"true-class": isTrue, "false-class": !isTrue})
Parth Developer
  • 1,371
  • 1
  • 13
  • 30