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


Question

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.

1
64
1/3/2013 5:45:13 PM

Accepted Answer

This works:

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

Try it out here.

100
1/3/2013 5:48:28 PM

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')

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon