2015-02-10 71 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把手模板逻辑运算符(的