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

别来无恙 提交于 2019-12-17 22:33:24

问题


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:


This works:

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

Try it out here.




回答2:


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



回答3:


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 .




回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/14144274/jade-conditional-if-else-to-add-class-to-div-inline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!