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

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


This works:

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

Try it out here.


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


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 .