问题
Wondering if there is a way to write a ternary, or shorter form of if statement, which adds the 'a' element to the table cell when the if is satisfied.
I tried this, but it doesn't work:
td= foo.x ? a(href="/#{foo.x}/foobar") View : '-'
The following does work, but is quite long winded and untidy..
tbody
each foo in bar
tr
td= foo.name
if foo.x
td
a(href="/#{foo.x}/foobar") View
else
td -
if foo.y
td
a(href="/#{foo.y}/hello") Hello
else
td -
Thanks
回答1:
No. There is no ternary operator (that I know of!) in Jade.As it turns out, there is a ternary operator. However, to shorten your code, what you could do is declare blocks and use them in your if/else sections. While this technically adds lines to your code, I think this helps you with your problem of long if/else statements.
Using your example:
block x_view
td
a(href="/#{foo.x}/foobar") View
block dash
td -
block y_hello
td
a(href="/#{foo.y}/hello") Hello
tbody
each foo in bar
tr
td= foo.name
if foo.x
block x_view
else
block dash
if foo.y
block y_hello
else
block dash
回答2:
Ternaries work fine in jade.
I did a quick working example loosely based on your question:
- var bar=[{name:'Joe',x:'something'},{name:'Mike'}]
each foo in bar
p=foo.x ? foo.name + ' hasX' : foo.name + ' noX'
results in
<p>Joe hasX</p>
<p>Mike noX</p>
回答3:
You can also use #{}
:
h6 #{(employee.Sprite > 0) ? "SPRITE" : "NO SPRITE"}
Where employee.Sprite is a number in the data...
来源:https://stackoverflow.com/questions/21492450/jade-ternary-operator-add-element