2015-02-10 66 views
4

我有以下代碼:spacebars:如何使用和/或if語句

<div class="form-group {{#if afFieldIsInvalid name='latitude' OR name='longitude'}}has-error{{/if}}">......</div> 

我如何/或是否使用和spacebars模板條件是什麼?

+0

可能重複http://stackoverflow.com/questions/17252750/meteor-js-車把-模板邏輯運算符) – 2015-02-10 08:16:40

回答

8

Spacebars無法處理邏輯表達式,所以您需要創建一個幫助程序來處理您的計算。

其實,你可以用嵌套IFS這樣實現and功能:

{{#if condition1}} 
    {{#if condition2}} 
     <p>Both condition hold!</p> 
    {{/if}} 
{{/if}} 

而且or這樣的:

{{#if condition1}} 
    <p>One of the conditions are true!</p> 
{{else}} 
    {{#if condition2}} 
     <p>One of the conditions are true!</p> 
    {{/if}} 
{{/if}} 

但我寧願使用幫手。

-5

而不是使用'OR'嘗試'||'。 或者在JavaScript文件中定義一個方法。

0

您有針對這種情況設計的擴展。

Raix Handlebars

您可以使用一個 '與' 條件是這樣的:

{{#if $in yourVariable 'case1' 'case2' }} 
     Your code Here 
{{/if}} 
0

以解決一步。這增加了比較運算符。

Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) { 

    switch (operator) { 
     case '==': 
      return (v1 == v2) ? options.fn(this) : options.inverse(this); 
     case '===': 
      return (v1 === v2) ? options.fn(this) : options.inverse(this); 
     case '!=': 
      return (v1 != v2) ? options.fn(this) : options.inverse(this); 
     case '!==': 
      return (v1 !== v2) ? options.fn(this) : options.inverse(this); 
     case '<': 
      return (v1 < v2) ? options.fn(this) : options.inverse(this); 
     case '<=': 
      return (v1 <= v2) ? options.fn(this) : options.inverse(this); 
     case '>': 
      return (v1 > v2) ? options.fn(this) : options.inverse(this); 
     case '>=': 
      return (v1 >= v2) ? options.fn(this) : options.inverse(this); 
     case '&&': 
      return (v1 && v2) ? options.fn(this) : options.inverse(this); 
     case '||': 
      return (v1 || v2) ? options.fn(this) : options.inverse(this); 
     default: 
      return options.inverse(this); 
    } 
}); 

使用它在這樣的模板:

{{#ifCond name='latitude' '||' name='longitude'}} 
[Meteor.js把手模板邏輯運算符(的