jade - 如果var不等于数组中的任何元素,则显示foo

时间:2013-04-28 21:00:29

标签: pug

如果变量(curBranch)不等于数组中的任何元素(user.subscribed),或者“unsubscribe”按钮(如果不是),我想给用户一个'subscribe'按钮。我试过这个:

- if (user != null)
  isSubscribed = false
  each subscription in user.subscribed
    - if (subscription === curBranch)
      isSubscribed = true
      form(action='/unsubscribe/#{curBranch}')
        button(type='submit') Unsubscribe

  - if (isSubscribed === false)
    form(action='/subscribe/#{curBranch}')
      button(type='submit') subscribe

第一部分(换行前)完美运作。但是,在for循环完成之前,jade似乎执行了第三个if语句。

有没有办法让这个顺序运行,或者,我应该使用不同的方法吗?

2 个答案:

答案 0 :(得分:6)

你应该使用Array.indexOf()代替循环:

-if (user != null)
  -if (user.subscribed.indexOf(curBranch) > -1)
    form(action='/unsubscribe/#{curBranch}')
      button(type='submit') Unsubscribe
  -else
    form(action='/subscribe/#{curBranch}')
      button(type='submit') subscribe

警告:indexOf IE仅支持comes with IE9。如果您正在运行jQuery,则可以使用下划线来使用$.inArray(value, array)_.contains(list, value)

答案 1 :(得分:1)

试试这个:

if user != null
isSubscribed = false
each subscription in user.subscribed
  if subscription == curBranch
    isSubscribed = true
    form(action='/unsubscribe/#{curBranch}')
      button(type='submit') Unsubscribe

if isSubscribed == false
  form(action='/subscribe/#{curBranch}')
    button(type='submit') subscribe