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

Javascriptnode.jsExpressPug

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

This works:

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

Try it out here.

Solution 2 - Javascript

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

Solution 3 - Javascript

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] .

Solution 4 - Javascript

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

Solution 5 - Javascript

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.

Solution 6 - Javascript

Multiple conditional classes

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionjstevens13View Question on Stackoverflow
Solution 1 - JavascriptDogbertView Answer on Stackoverflow
Solution 2 - JavascriptArkanoidView Answer on Stackoverflow
Solution 3 - JavascriptinfografnetView Answer on Stackoverflow
Solution 4 - JavascriptbravedickView Answer on Stackoverflow
Solution 5 - JavascriptMatthew SundbergView Answer on Stackoverflow
Solution 6 - JavascriptParth DeveloperView Answer on Stackoverflow