Jade ternary operator add element

…衆ロ難τιáo~ 提交于 2020-05-25 07:41:45

问题


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

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