Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jade ternary operator add element

Tags:

pug

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

like image 299
gratz Avatar asked Feb 01 '14 00:02

gratz


3 Answers

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>
like image 140
rjreed Avatar answered Nov 23 '22 19:11

rjreed


You can also use #{}:

h6 #{(employee.Sprite > 0) ? "SPRITE" : "NO SPRITE"}

Where employee.Sprite is a number in the data...

like image 29
Jason Lydon Avatar answered Nov 23 '22 19:11

Jason Lydon


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
like image 44
Avery Avatar answered Nov 23 '22 17:11

Avery